【问题标题】:subprocess.Popen() - does order matter for p.stdout.read() and p.wait()?subprocess.Popen() - p.stdout.read() 和 p.wait() 的顺序是否重要?
【发布时间】:2012-07-02 10:47:17
【问题描述】:

关于 Python 的 subprocess.Popen() 对象的问题
(请假设为 stdout/stderr 生成的字节数没有填满 OS 管道缓冲区并创建死锁以等待 OS 管道缓冲区接受更多数据)

1) p.stdout.read() 和 p.wait() 的顺序有关系吗?

2) stdout/stderr subprocess.PIPE 上的 read() 是否会阻塞,直到进程终止?

3) 即使在进程终止后,stdout/stderr subprocess.PIPE 文件对象和数据是否可用?

import subprocess
process = subprocess.Popen(args="ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout = process.stdout.read()
# Does the above read() block until the process has terminated?
stderr = process.stderr.read()
return_code = process.wait()

process = subprocess.Popen(args="ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
return_code = process.wait() 
# Are stdout and stderr pipes available now, even after the process terminated?
stdout = process.stdout.read()
stderr = process.stderr.read()

【问题讨论】:

  • 如果您所做的只是读取输出,我强烈推荐.communicate() 而不是.read()+.wait()

标签: python subprocess


【解决方案1】:

问:p.stdout.read() 和 p.wait() 的顺序有关系吗?
答:没有。

问:stdout/stderr subprocess.PIPE 上的 read() 是否会阻塞,直到进程终止?
A:如果没有指定读取字节数的限制,那么它会一直阻塞,直到流被关闭(很可能在进程终止时)。

问:即使在进程终止后,stdout/stderr subprocess.PIPE 文件对象和数据是否可用?
答:是的。

您可能需要特别注意subprocess 文档中的此警告:

警告:当使用stdout=PIPE 和/或stderr=PIPE 时,这将死锁,并且子进程会向管道生成足够的输出,从而阻塞等待操作系统管道缓冲区接受更多数据。使用communicate() 来避免这种情况。

【讨论】:

  • 谢谢琥珀。我知道死锁警告,但假设 stdout/stderr 数据很小(例如,每个
  • 在这种情况下,这无关紧要 - 任何一个调用都不应比另一个调用阻塞更长的时间。
【解决方案2】:

您可能需要考虑使用像sarge 这样的库,它可以在对子进程进行 I/O 时提供灵活性。 (披露:我是维护者。我写它部分是为了回应你遇到的那种困难。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2011-06-02
    相关资源
    最近更新 更多