Python:如何启动完整进程而不是子进程并检索PID
我想:Python:如何启动完整进程而不是子进程并检索PID,python,windows,process,Python,Windows,Process,我想: 从我的进程(myexe.exe arg0)启动新进程(myexe.exe arg1) 检索此新进程的PID(操作系统windows) 当我使用TaskManager Windows命令“结束进程树”杀死我的第一个实体(myexe.exe arg0)时,我需要新实体(myexe.exe arg1)不会被杀死 我已经玩过subprocess.Popen、os.exec、os.spawn、os.system。。。没有成功 另一种解释问题的方法是:如果有人杀死myexe.exe(arg0)的“进
subprocess.Popen(["myexe.exe",arg[1]],creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,close_fds = True)
几年前,我在windows上也做了类似的事情,我的问题是想杀死子进程 我假设您可以使用
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.
要启动父进程退出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进程创建标志为
.因此,如果我理解正确,代码应该是这样的:
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)
至少我试过这一个,并为我工作。你有任何到目前为止你所做工作的示例代码吗?相关:可能与nice try重复!但是当我通过windows的“结束进程树”taskmanager命令杀死“myexe.exe”(arg0)时,两个myexe.exe都被杀死了!如果我对“myexe.exe”(arg1)执行了相同的命令,那么只有这个实体会被杀死…@baco:使用只杀死一个进程的选项,而不是“进程树”。可能进程树是双向遍历的。@JF Sebastian:问题=>如果有人杀死myexe.exe(arg0)的“进程树”,如何保护myexe.exe(arg1)(解决方案似乎使用os.startfile,但我不能使用args!)@baco:尝试从
arg0
启动一个中间进程X
,该进程只启动arg1
并立即退出(您可以通过X
的标准输出读取arg0
中孙子的pid)。