subprocess


Run external command and capture the output


examples/process/slow.py
import time
import sys

for i in range(3):
   print("OUT {}".format(i))
   print("ERR {}".format(i), file=sys.stderr)
   time.sleep(1)

examples/process/run_command.py
import subprocess
import sys

command = [sys.executable, 'slow.py']

proc = subprocess.Popen(command,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
)

out,err = proc.communicate()  # runs the code

# out and err are two strings

print('exit code:', proc.returncode)

print('out:')
for line in out.decode('utf8').split('\n'):
    print(line)

print('err:')
for line in err.decode('utf8').split('\n'):
    print(line)

In this example p is an instance of the subprocess.PIPE class. The command is executed when the object is created.