你可以尝试使用subprocess.PIPE,假设你想避免使用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())
对于Python 3记住这里使用会返回一个byte
对象,而不是一个字符串communicate()
方法。 :
在这种情况下,你需要将输出转换为使用decode()
字符串:
if err:
print(err.strip().decode())
if out:
print(out.strip().decode())
来源
2016-02-13 04:23:58
Joe
管是壳的东西。 shell会分叉两个子进程,并且将第一个子进程的stdout转换为第二个子进程的stdin。你需要自己实现这个逻辑。 – sturcotte06