我想:
我玩过subprocess.Popen,os.exec,os.spawn,os.system ......但没有成功。
另一种解释问题的方法:如果有人杀死了myexe.exe(arg0)的“进程树”,如何保护myexe.exe(arg1)?
编辑:同一个问题(没有回答)HERE
编辑:以下命令不保证子进程的独立性
subprocess.Popen(["myexe.exe",arg[1]],creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,close_fds = True)
答案 0 :(得分:7)
启动可在父进程退出Windows后继续运行的子进程:
from subprocess import Popen, PIPE
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
p = Popen(["myexe.exe", "arg1"], stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
print(p.pid)
Windows进程创建标志为here
答案 1 :(得分:1)
我认为你可以使用pid = Popen(["/bin/mycmd", "myarg"]).pid
来运行子进程,所以我不确定真正的问题是什么,所以我猜这是你杀死主进程的时候。
我无法证明这一点,因为我没有运行Windows。
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen is created with shell=True.
subprocess.CREATE_NEW_PROCESS_GROUP
A Popen creationflags parameter to specify that a new process group will be created. This flag is necessary for using os.kill() on the subprocess.
This flag is ignored if CREATE_NEW_CONSOLE is specified.
答案 2 :(得分:1)
因此,如果我理解你,代码应该是这样的:
from subprocess import Popen, PIPE
script = "C:\myexe.exe"
param = "-help"
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
pid = Popen([script, param], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
至少我试过这个并为我工作。