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

bac*_*aco 10 python windows process

我想要:

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

我玩过subprocess.Popen,os.exec,os.spawn,os.system ......但没有成功.

另一种解释问题的方法:如果有人杀死了myexe.exe(arg0)的"进程树",如何保护myexe.exe(arg1)?

编辑:同样的问题(没有答案)在这里

编辑:以下命令不保证子进程的独立性

subprocess.Popen(["myexe.exe",arg[1]],creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,close_fds = True)
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 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)
Run Code Online (Sandbox Code Playgroud)

Windows进程创建标志在这里

这里有一个更便携的版本.


sot*_*pme 1

几年前我在 Windows 上做了类似的事情,我的问题是想要终止子进程。

\n\n

我想你可以使用运行子进程pid = Popen(["/bin/mycmd", "myarg"]).pid\n,所以我不确定真正的问题是什么,所以我猜测是当你杀死主进程时。

\n\n

IIRC 这与标志有关。

\n\n

我无法证明这一点,因为我运行的不是 Windows。

\n\n
subprocess.CREATE_NEW_CONSOLE\nThe new process has a new console, instead of inheriting its parent\xe2\x80\x99s console (the default).\n\nThis flag is always set when Popen is created with shell=True.\n\nsubprocess.CREATE_NEW_PROCESS_GROUP\nA Popen creationflags parameter to specify that a new process group will be created. This flag is necessary for using os.kill() on the subprocess.\n\nThis flag is ignored if CREATE_NEW_CONSOLE is specified.\n
Run Code Online (Sandbox Code Playgroud)\n