如果父进程创建了一个子进程,则subprocess.communicate()在Windows 8上挂起

时间:2013-05-13 13:56:44

标签: python windows subprocess

我有一个简单的代码,可以在Win 2003上正常工作:

proc = subprocess.Popen('<some python script which runs another process>', stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE)
out = proc.communicate()[0]

但是在Windows 8这部分; out = proc.communicate()[0],挂起。

有人看过这个问题吗?

  • 我已检查过程是否真的已经过时(启动子进程时PID不存在)
  • 制作proc.stdout.readlines()也是一个问题,它也会挂起。如何检查stdout是否有EOF?
  • 当我停止子进程proc.communicate()工作正常。

这是最简单的例子:

import subprocess
proc = subprocess.Popen([sys.executable, "D:\\test.py"], stdout = subprocess.PIPE)
print 'PID', proc.pid #When this PID is printed I see in the taskbr that process is already finished
print 'Output', proc.communicate() # but this part is hangs

和代码od test.py:

import os, time
from subprocess import Popen, PIPE

CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208


p = Popen("start /B notepad", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE,
          creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
print 'Done'
exit()

这是有效的情况吗?

1 个答案:

答案 0 :(得分:2)

要允许.communicate()返回而不等待孙子(记事本)退出,您可以尝试test.py

import sys
from subprocess import Popen, PIPE

CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008

p = Popen('grandchild', stdin=PIPE, stdout=PIPE, stderr=PIPE,
          creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)

请参阅Popen waiting for child process even when the immediate child has terminated