Skip to content
Advertisement

How to find pid of a process by Python?

friends:

I am running a script in Linux:

I can use the ps command get the process.

JavaScript

but, how can I know the pid of the running script by given key word python test09.py& using python code?


EDIT-01

I mean, I want to use the python script to find the running script python test09.py&‘s pid.


EDIT-02

When I run anali’s method I will get this error:

JavaScript

Advertisement

Answer

If you just want the pid of the current script, then use os.getpid:

JavaScript

However, below is an example of using psutil to find the pids of python processes running a named python script. This could include the current process, but the main use case is for examining other processes, because for the current process it is easier just to use os.getpid as shown above.

sleep.py

JavaScript

get_pids.py

JavaScript

Running it:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement