4

我有一个在 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()也是一个问题,它也挂了。如何检查标准输出是否有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()

这是有效的场景吗?

4

1 回答 1

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 即使直接子进程已终止

于 2013-05-14T11:42:44.140 回答