26

I want to get the process name, given it's pid in python. Is there any direct method in python?

2
  • What do you mean "per line"? Commented Aug 30, 2015 at 10:14
  • It means that print pid and its name per line. not important Commented Aug 30, 2015 at 11:03

3 Answers 3

50

The psutil package makes this very easy.

import psutil

process = psutil.Process(pid)

process_name = process.name()
Sign up to request clarification or add additional context in comments.

3 Comments

This is the better module. I was trying to remember what this was called. It wasn't procfs.
I get an error: 'TypeError: 'str' object is not callable'
@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.
5

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

@Mahsa just use that function in a loop ie for a list of pid, just loop through that list and use the function
when you return os.system("whatever") you are probably getting the exitcode (0) rather than the string that the command outputs
0

Command 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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.