Python:如何启动一个完整的进程而不是子进程并检索 PID [英] Python: Howto launch a full process not a child process and retrieve the PID

查看:27
本文介绍了Python:如何启动一个完整的进程而不是子进程并检索 PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:

  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)?

同样的问题(没有答案)这里

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

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

解决方案

在 Windows 上启动一个可以在父进程退出后继续运行的子进程:

from subprocess import Popen, PIPECREATE_NEW_PROCESS_GROUP = 0x00000200DETACHED_PROCESS = 0x00000008p = Popen(["myexe.exe", "arg1"], stdin=PIPE, stdout=PIPE, stderr=PIPE,creationflags=DETACHED_PROCESS |CREATE_NEW_PROCESS_GROUP)打印(p.pid)

Windows 进程创建标志是 这里

更便携的版本在这里.

I would like:

  1. Launch a new process (myexe.exe arg1) from my process (myexe.exe arg0)
  2. Retrieve the PID of this new process (os windows)
  3. when I kill my first entity (myexe.exe arg0) with the TaskManager Windows Command "End process tree", I need that the new one (myexe.exe arg1) will not be killed...

I've played with subprocess.Popen, os.exec, os.spawn, os.system... without success.

Another way to explain the problem: How to protect myexe.exe (arg1) if someone kills the "process tree" of the myexe.exe (arg0)?

EDIT: same question (without answer) HERE

EDIT: the following command do not guarantee the Independence of the subprocess

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

解决方案

To start a child process that can continue to run after the parent process exits on 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 process creation flags are here

A more portable version is here.

这篇关于Python:如何启动一个完整的进程而不是子进程并检索 PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆