我与Python 2.7在Windows 8 / XP工作。
我有使用以下代码运行另一个节目B的程序的:
p = Popen(["B"], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return
乙运行批处理脚本C. C是一个长期运行的脚本,我想虽然C已没有完成B到甚至退出。 我曾尝试使用下面的代码(B)做到了:
p = Popen(["C"])
return
当我运行B,它按预期工作。 当我运行一个不过,我预期B出口退出时。 但A等待,直到ç退出,即使B已经exitted。 什么任何想法是怎么回事,可能是什么可能的解决方案?
不幸的是,改变看起来像B的明显的解决方案是不是一种选择。
这是一个功能的示例代码来说明这个问题: https://www.dropbox.com/s/cbplwjpmydogvu2/popen.zip?dl=1
任何输入是非常赞赏。
你可以提供start_new_session
为模拟C
子:
#!/usr/bin/env python
import os
import sys
import platform
from subprocess import Popen, PIPE
# set system/version dependent "start_new_session" analogs
kwargs = {}
if platform.system() == 'Windows':
# from msdn [1]
CREATE_NEW_PROCESS_GROUP = 0x00000200 # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008 # 0x8 | 0x200 == 0x208
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
elif sys.version_info < (3, 2): # assume posix
kwargs.update(preexec_fn=os.setsid)
else: # Python 3.2+ and Unix
kwargs.update(start_new_session=True)
p = Popen(["C"], stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
assert not p.poll()
[1]: 进程创建旗帜为的CreateProcess()
这是改编自塞巴斯蒂安的答案和代码片断这个答案:
#!/usr/bin/env python
import os
import sys
import platform
from subprocess import Popen, PIPE
# set system/version dependent "start_new_session" analogs
kwargs = {}
if platform.system() == 'Windows':
# from msdn [1]
CREATE_NEW_PROCESS_GROUP = 0x00000200 # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008 # 0x8 | 0x200 == 0x208
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, close_fds=True)
elif sys.version_info < (3, 2): # assume posix
kwargs.update(preexec_fn=os.setsid)
else: # Python 3.2+ and Unix
kwargs.update(start_new_session=True)
p = Popen(["C"], stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
assert not p.poll()
我只测试了它亲自在Windows上。
文章来源: Popen waiting for child process even when the immediate child has terminated