getting ProcessId within Python code

后端 未结 4 1009
渐次进展
渐次进展 2021-01-01 16:19

I am in Windows and Suppose I have a main python code that calls python interpreter in command line to execute another python script ,say test.py .

So test.py is exe

相关标签:
4条回答
  • 2021-01-01 16:54

    It all depends on how you're launching the second process.

    If you're using os.system or similar, that call won't report back anything useful about the child process's pid. One option is to have your 2nd script communicate the result of os.getpid() back to the original process via stdin/stdout, or write it to a predetermined file location. Another alternative is to use the third-party psutil library to figure out which process it is.

    On the other hand, if you're using the subprocess module to launch the script, the resulting "popen" object has an attribute popen.pid which will give you the process id.

    0 讨论(0)
  • 2021-01-01 16:55

    Another option is that the process you execute will set a console window title for himself. And the searching process will enumerate all windows, find the relevant window handle by name and use the handle to find PID. It works on windows using ctypes.

    0 讨论(0)
  • 2021-01-01 17:06

    If you used subprocess to spawn the shell, you can find the process ID in the pid property:

    sp = subprocess.Popen(['python', 'script.py'])
    print('PID is ' + str(sp.pid))
    

    If you used multiprocessing, use its pid property:

    p = multiprocessing.Process()
    p.start()
    # Some time later ...
    print('PID is ' + str(p.pid))
    
    0 讨论(0)
  • 2021-01-01 17:13

    You will receive the process ID of the newly created process when you create it. At least, you will if you used fork() (Unix), posix_spawn(), CreateProcess() (Win32) or probably any other reasonable mechanism to create it.

    If you invoke the "python" binary, the python PID will be the PID of this binary that you invoke. It's not going to create another subprocess for itself (Unless your python code does that).

    0 讨论(0)
提交回复
热议问题