在python子进程文档中,有一个示例,该示例从具有超时的进程获取输出: https://docs.python.org/3.6/library/subprocess.html#subprocess.Popen.communicate如下:
proc = subprocess.Popen(...)
try:
outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
我尝试了上述操作,但在超时后无法捕获标准输出(启动Django)。我在SO上看到类似的问题,其答案引用了上面的代码,例如: https://stackoverflow.com/a/43522045/5506400
完成上述SO答案的代码并运行它:
import subprocess
proc = subprocess.Popen(
["ping", "192.168.1.150"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
try:
output, error = proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
output, error = proc.communicate()
print('outputs:', output) # output is ''
print('errs:', error) # error is ''
此代码也不会捕获从进程开始到超时的输出。该帖子上有评论说它不起作用,但也有5票赞成票。因此,我不确定要推断它是否应该工作。也许我们一半人失踪了?