python run a command line code example

Example 1: execute command in python script

import os

os.system("ma Commande")

#Exemple:

os.system("cd Documents")

Example 2: run python.py file

# save a file in text editor with .py
# open terminal, and change directories
# run the following command:
python3 file.py

Example 3: call shell script from python

import subprocess
subprocess.call(["./shell.sh"])

# Make sure that "shell.sh" has "+x" permissions

Example 4: python if run in terminal

import sys
if sys.stdin.isatty():
    # running interactively
    print "running interactively"
else:
    with open('output','w') as f:
        f.write("running in the background!\n")