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,
    shell=True)

out,err = p.communicate()

print('err:' , err)
print('out:')
for e in out.split('\n'):
    print(e)

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