Run external command and capture the output

from __future__ import print_function
import subprocess
import sys

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

proc = subprocess.Popen(command,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
) # runs the code

out,err = proc.communicate()

# out and err are two strings

print('exit code:', proc.returncode)
print('err:' , err)
for line in out.split('\n'):

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