Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

windows - Python: Howto launch a full process not a child process and retrieve the PID

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...