开发者

getting ProcessId within Python code

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 executed as a new process.How can I find the processId for this porcess in Python ?

Update:

To be more specific , we have os.getpid() in os module. It returns the current process id.

If I have a main program that runs Python interpreter to run another script ,开发者_开发技巧 how can I get the process Id for that executing script ?


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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜