子进程:假设 wait() 终止,communicate() 会超时吗?

subprocess: Can communicate() timeout, given that wait() terminates?

Popen.communicate(timeout=2) 是否有可能加注 TimeoutExpired,即使我断言 Popen.poll() is not NonePopen.wait(2) 不会 ] 抛出异常?

编辑:docs 建议使用以下代码段:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

但这只会加注 ProcessLookupError: [Errno 3] No such process。这是有道理的,因为我已经通过 pollwait.

终止了进程

是的。如果 child 产生它自己的子进程是可能的。 Popen.communicate() 可能 return 比只等待 child 的 Popen.wait() 晚得多。参见

注意:proc.kill() 可能不会终止整个进程树。参见 How to terminate a python subprocess launched with shell=True