2013-02-10 66 views
4

我想:的Python:HOWTO推出全过程不是一个子进程,并取回PID

  1. 启动一个新的进程(MYEXE.EXE ARG1)从我的过程(MYEXE.EXE为arg0)
  2. 检索这个新进程的PID(操作系统窗口)
  3. 当我用TaskManager Windows命令“结束进程树”杀死我的第一个实体(myexe.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) 
+0

到目前为止,你有没有任何示例代码? – sotapme 2013-02-10 11:30:42

+0

相关:[即使当眼前的孩子已经终止,Popen等待子进程](http://stackoverflow.com/questions/13243807/popen-waiting-for-child-process-even-when-the-immediate-child-已终止) – jfs 2013-02-10 11:43:31

+1

[从Python启动完全独立的进程]可能的重复(http://stackoverflow.com/questions/13592219/launch-a-totally-independent-process-from-python) – jtpereyda 2017-02-28 03:21:59

回答

1

我做了类似几年前在Windows和我的问题想要杀死孩子的过程。

我认为你可以使用pid = Popen(["/bin/mycmd", "myarg"]).pid 来运行子流程,所以我不确定真正的问题是什么,所以我猜这是你杀死主流程的时候。

IIRC这是与国旗有关的事情。

我不能证明它,因为我没有运行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. 
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

+0

不错的尝试! 但是当我通过Windows的“结束进程树”taskmanager命令杀死“myexe.exe”(arg0)时,两个myexe.exe都被杀死了! 如果我在“myexe.exe”(arg1)上做了同样的命令,只有这个实体会被杀死...... – baco 2013-02-10 13:31:35

+0

@baco:使用杀死只有一个进程而不是“进程树”的选项。 – jfs 2013-02-10 13:38:07

+0

可能是进程树在两个方向上遍历。 – nikola 2013-02-10 13:39:41

0

所以,如果我理解你正确的代码应该是这样的:

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) 

至少我尝试这样一个为我工作。