How to Get the Process Name by Pid in Linux Using Python

How to get PID by process name?

You can get the pid of processes by name using pidof through subprocess.check_output:

from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])

In [5]: get_pid("java")
Out[5]: '23366\n'

check_output(["pidof",name]) will run the command as "pidof process_name", If the return code was non-zero it raises a CalledProcessError.

To handle multiple entries and cast to ints:

from subprocess import check_output
def get_pid(name):
return map(int,check_output(["pidof",name]).split())

In [21]: get_pid("chrome")

Out[21]: 
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]

Or pas the -s flag to get a single pid:

def get_pid(name):
return int(check_output(["pidof","-s",name]))

In [25]: get_pid("chrome")
Out[25]: 27698

How to get the process name by pid in Linux using Python?

If you want to see the running process, you can just use os module to execute the ps unix command

import os
os.system("ps")

This will list the processes.

But if you want to get process name by ID, you can try ps -o cmd= <pid>
So the python code will be

import os
def get_pname(id):
return os.system("ps -o cmd= {}".format(id))
print(get_pname(1))

The better method is using subprocess and pipes.

import subprocess
def get_pname(id):
p = subprocess.Popen(["ps -o cmd= {}".format(id)], stdout=subprocess.PIPE, shell=True)
return str(p.communicate()[0])
name = get_pname(1)
print(name)

Get process name by PID

Under Linux, you can read proc filesystem. File /proc/<pid>/cmdline contains the commandline.

How to find pid of a process by Python?

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]

Get the process name by pid

You can directly obtain this information from the /proc file system if you don't want to use a separate library like psutil.

import os
import signal

pid = '123'
name = 'pfinder'

pid_path = os.path.join('/proc', pid)
if os.path.exists(pid_path):
with open(os.join(pid_path, 'comm')) as f:
content = f.read().rstrip('\n')

if name == content:
os.kill(pid, signal.SIGTERM)
   /proc/[pid]/comm (since Linux 2.6.33)
This file exposes the process's comm value—that is, the
command name associated with the process. Different threads
in the same process may have different comm values, accessible
via /proc/[pid]/task/[tid]/comm. A thread may modify its comm
value, or that of any of other thread in the same thread group
(see the discussion of CLONE_THREAD in clone(2)), by writing
to the file /proc/self/task/[tid]/comm. Strings longer than
TASK_COMM_LEN (16) characters are silently truncated.

This file provides a superset of the prctl(2) PR_SET_NAME and
PR_GET_NAME operations, and is employed by
pthread_setname_np(3) when used to rename threads other than
the caller.

How do you get the process ID of a program in Unix or Linux using Python?

Try pgrep. Its output format is much simpler and therefore easier to parse.

How to get the pid of process using python

similar to the answers above, but from the question it seems you are only interested in a subset of all running tasks (e.g. firefox, atom and gnome-shell)

you can put the tasks you are interested in into a list..then loop through all of the processes, only appending the ones matching your list to the final output, like so:

import psutil

tasklist=['firefox','atom','gnome-shell']
out=[]

for proc in psutil.process_iter():
if any(task in proc.name() for task in tasklist):
out.append([{'pid' : proc.pid, 'name' : proc.name()}])

this will give you your desired output of a list of lists, where each list has a dictionary with the pid and name keys...you can tweak the output to be whatever format you like however

the exact output you requested can be obtained by:

for o in out[:]:
print(o)


Related Topics



Leave a reply



Submit