非常具體的問題(我希望):以下三個代碼有什麼區別?Python子進程Popen.communicate()等價於Popen.stdout.read()?
(我希望它是隻有第一沒有等待子進程來完成,而第二個和第三個做,但我需要確保這是唯一差異 ... )
我也歡迎其他評論/建議(雖然我已深知shell=True
危險和跨平臺的限制)
注意的,我已經閱讀Python subprocess interaction, why does my process work with Popen.communicate, but not Popen.stdout.read()?,而我不希望/需要互動與程序之後。
另外請注意,我已經讀過Alternatives to Python Popen.communicate() memory limitations?但我並沒有真正得到它...
最後請注意,我知道冥冥之中有當一個緩衝區填充了一個輸出僵局的風險使用一種方法,但同時尋找在互聯網上解釋清楚我迷路了......
首先代碼:
from subprocess import Popen, PIPE
def exe_f(command='ls -l', shell=True):
"""Function to execute a command and return stuff"""
process = Popen(command, shell=shell, stdout=PIPE, stderr=PIPE)
stdout = process.stdout.read()
stderr = process.stderr.read()
return process, stderr, stdout
二碼:
from subprocess import Popen, PIPE
from subprocess import communicate
def exe_f(command='ls -l', shell=True):
"""Function to execute a command and return stuff"""
process = Popen(command, shell=shell, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = process.communicate()
return process, stderr, stdout
第三碼:
from subprocess import Popen, PIPE
from subprocess import wait
def exe_f(command='ls -l', shell=True):
"""Function to execute a command and return stuff"""
process = Popen(command, shell=shell, stdout=PIPE, stderr=PIPE)
code = process.wait()
stdout = process.stdout.read()
stderr = process.stderr.read()
return process, stderr, stdout
感謝。