You could try using subprocess.PIPE, assuming you wanted to avoid using subprocess.call(..., shell=True)
.
import subprocess
# Run 'ls', sending output to a PIPE (shell equiv.: ls -l | ... )
ls = subprocess.Popen('ls -l folder'.split(),
stdout=subprocess.PIPE)
# Read output from 'ls' as input to 'wc' (shell equiv.: ... | wc -l)
wc = subprocess.Popen('wc -l'.split(),
stdin=ls.stdout,
stdout=subprocess.PIPE)
# Trap stdout and stderr from 'wc'
out, err = wc.communicate()
if err:
print(err.strip())
if out:
print(out.strip())
For Python 3 keep in mind the communicate()
method used here will return a byte
object instead of a string. :
In this case you will need to convert the output to a string using decode()
:
if err:
print(err.strip().decode())
if out:
print(out.strip().decode())