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']

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

out,err = p.communicate()

# out and err are two strings

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.