needleinthehay.de

Execute external Commands

Warning: executing shell command like this can be dangerous!

Run & get output and result code:

import subprocess

p = subprocess.Popen("[ where is my coffee?",
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

proc_lines = p.stdout.readlines()
proc_code = p.wait()

print(f"Process return code: {proc_code}")
for line in proc_lines:
    print(line.decode())

# OUT:
# Process return code: 2
# /bin/sh: line 0: [: missing `]'

Run & get only resulting lines only:

import subprocess

proc_lines = subprocess.check_output("[ where is my coffee?; exit 0",
                                     shell=True)
for line in proc_lines:
    print(line.decode())

# OUT:
# /bin/sh: line 0: [: missing `]'

Run & get only status code: (output is still printed on screen)

import subprocess

proc_code = subprocess.call("[ where is my coffee?; exit 0",
                            shell=True)

print(f"Process return code: {proc_code}")

# OUT:
# Process return code: 0