Run external command and capture the output

examples/os/run_command.py
from __future__ import print_function
import subprocess
import sys

command = ['ls', '-l']
if sys.platform == 'win32':
    command = ['dir']

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

out,err = p.communicate()

# out and err are two strings

print('err:' , err)
print('out:')
for line in out.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.