【发布时间】:2012-10-18 22:59:05
【问题描述】:
非常具体的问题(希望如此):以下三个代码有什么区别?
(我希望它只是第一个不等待子进程完成,而第二个和第三个等待子进程完成。但我需要确保这是 only 的区别...)
我也欢迎其他评论/建议(尽管我已经很清楚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
谢谢。
【问题讨论】:
标签: python subprocess wait popen communicate