【问题标题】:Python: Howto launch a full process not a child process and retrieve the PIDPython:如何启动一个完整进程而不是子进程并检索 PID
【发布时间】:2013-01-25 16:11:51
【问题描述】:

我想要:

  1. 从我的进程 (myexe.exe arg0) 启动一个新进程 (myexe.exe arg1)
  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)

【问题讨论】:

标签: python windows process


【解决方案1】:

在 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.

【讨论】:

  • 不错的尝试!但是当我通过windows的“结束进程树”任务管理器命令杀死“myexe.exe”(arg0)时,myexe.exe都被杀死了!如果我在“myexe.exe”(arg1)上执行了相同的命令,那么只有这个实体会被杀死......
  • @baco:使用只杀死一个进程而不是“进程树”的选项。
  • 可能进程树是双向遍历的。
  • @JF Sebastian:这个问题=>如果有人杀死了myexe.exe(arg0)的“进程树”,如何保护myexe.exe(arg1)(解决方案似乎使用os. startfile 但我不能使用 args!)
  • Windows 进程创建标志(现在)也可用作subprocesswindows constants
【解决方案2】:

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

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)

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

【讨论】:

  • 为什么 DETACHED_PROCESS = 0x00000008 ?
【解决方案3】:

几年前我在 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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2014-07-15
    • 2014-06-25
    相关资源
    最近更新 更多