Python:如何启动完整进程而不是子进程并检索PID

2024-09-24 22:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想:

  1. 从我的进程(my exe.exe arg0)启动新进程(myexe.exe arg1)
  2. 检索此新进程(os windows)的PID
  3. 当我使用TaskManager Windows命令“结束进程树”杀死第一个实体(my exe.exe arg0)时,我需要新实体(myexe.exe arg1)不会被杀死。。。

我玩过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)

Tags: 命令实体编辑进程osmywindowsprocess
3条回答

要启动在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

A more portable version is here

所以,如果我理解正确,代码应该如下:

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)

至少我试过这个,为我工作过。

几年前我在windows上也做过类似的事情,我的问题是想终止child进程。

我想您可以使用pid = Popen(["/bin/mycmd", "myarg"]).pid 运行子进程,所以我不确定真正的问题是什么,所以我猜是在您终止主进程时。

这和旗帜有关。

我不能证明,因为我没有开窗户。

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.

相关问题 更多 >