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.

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?


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:

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
    yield
  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 <module>
    print(get_pids_by_script_name('test09.py'))
  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)

Advertisement

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.

sleep.py

#!/usr/bin/env python
import time
time.sleep(100)

get_pids.py

import os
import psutil


def get_pids_by_script_name(script_name):

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

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

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

            pids.append(pid)

    return pids


print(get_pids_by_script_name('sleep.py'))

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]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement