• Uncategorized

About python : How-to-find-pid-of-a-process-by-Python

Question Detail

I am running a script in Linux:
I can use the ps command get the process.
ps -ef | grep “python test09.py&”

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

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

When I run anali’s method I will get this error:
Traceback (most recent call last):
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py”, line 363, in catch_zombie
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py”, line 429, in cmdline
return cext.proc_cmdline(self.pid)
ProcessLookupError: [Errno 3] No such process (originated from sysctl)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “test11.py”, line 29, in
File “test11.py”, line 15, in get_pids_by_script_name
cmdline = proc.cmdline()
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/__init__.py”, line 694, in cmdline
return self._proc.cmdline()
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py”, line 342, in wrapper
return fun(self, *args, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py”, line 429, in cmdline
return cext.proc_cmdline(self.pid)
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py”, line 77, in __exit__
self.gen.throw(type, value, traceback)
File “/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psutil/_psosx.py”, line 376, in catch_zombie
raise AccessDenied(proc.pid, proc._name)
psutil.AccessDenied: psutil.AccessDenied (pid=1)

Question Answer

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

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.
#!/usr/bin/env python
import time

import os
import psutil

def get_pids_by_script_name(script_name):

pids = []
for proc in psutil.process_iter():

cmdline = proc.cmdline()
pid = proc.pid
except psutil.NoSuchProcess:

if (len(cmdline) >= 2
and ‘python’ in cmdline[0]
and os.path.basename(cmdline[1]) == script_name):


return pids


Running it:
$ chmod +x sleep.py

$ cp sleep.py other.py

$ ./sleep.py &
[3] 24936

$ ./sleep.py &
[4] 24937

$ ./other.py &
[5] 24938

$ python get_pids.py
[24936, 24937]

Use this code and do a string matching against the cmd line
import psutil
# Iterate over all running process
for proc in psutil.process_iter():
# Get process name & pid & cmd line from process object.
processName = proc.name()
processID = proc.pid
print(processName , ‘ ::: ‘, processID)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):

Use Subprocess Library

import subprocess
script_name = “test09.py”
ps_out = subprocess.Popen(“ps -ef”.split(‘ ‘), stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read().decode(‘UTF-8’).split(“\n”) # Launch command line and gather output
for entry in ps_out: # Loop over returned lines of ps
if script_name in entry:
script_pid = entry.split()[1] # retrieve second entry in line

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.