I want to get the process name, given it's pid in python. Is there any direct method in python?
3 Answers
The psutil package makes this very easy.
import psutil
process = psutil.Process(pid)
process_name = process.name()
3 Comments
Paul
This is the better module. I was trying to remember what this was called. It wasn't procfs.
Mahsa
I get an error: 'TypeError: 'str' object is not callable'
Cyphase
@Mahsa, you're using an old version of
psutil. You should generally upgrade, but for now just use process.name as a string instead of calling it.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)
2 Comments
nishparadox
@Mahsa just use that function in a loop ie for a list of pid, just loop through that list and use the function
Octopus
when you
return os.system("whatever") you are probably getting the exitcode (0) rather than the string that the command outputsCommand name (only the executable name):
from subprocess import PIPE, Popen
def get_cmd(pid):
with Popen(f"ps -q {pid} -o comm=", shell=True, stdout=PIPE) as p:
return p.communicate()[0]
Command with all its arguments as a string:
from subprocess import PIPE, Popen
def get_args(pid):
with Popen(f"ps -q {pid} -o cmd=", shell=True, stdout=PIPE) as p:
return p.communicate()[0]