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

前端 未结 3 1857
感情败类
感情败类 2020-12-15 08:22

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
相关标签:
3条回答
  • 2020-12-15 08:50

    So if I understand you right the code should go like this:

    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)
    

    At least I tried this one and worked for me.

    0 讨论(0)
  • 2020-12-15 08:52

    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.

    0 讨论(0)
  • 2020-12-15 08:57

    I did similar a couple of years ago on windows and my issue was wanting to kill the child process.

    I presume you can run the subprocess using pid = Popen(["/bin/mycmd", "myarg"]).pid so I'm unsure what the real issue is, so I'm guessing it's when you kill the main process.

    IIRC it was something to do with the flags.

    I can't prove it as I'm not running 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.
    
    0 讨论(0)
提交回复
热议问题