你可以嘗試使用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