wong2
wong2

Reputation: 35750

How could I get the user name from a process id in python on Linux?

I want to get the user name from a process id in python on Linux, so I can show it like this:

name    user name   pid
Chrome  wong2       123

Upvotes: 3

Views: 8747

Answers (4)

user3552629
user3552629

Reputation: 81

If you do not want to parse the /proc/PID/status file and the process is not changing UID and if forking a process seems expensive to look up a username then try:

import os
import pwd
# the /proc/PID is owned by process creator
proc_stat_file = os.stat("/proc/%d" % pid)
# get UID via stat call
uid = proc_stat_file.st_uid
# look up the username from uid
username = pwd.getpwuid(uid)[0]

Upvotes: 8

Fred Foo
Fred Foo

Reputation: 363737

You can read the uid(s) from /proc/pid/status. They're in a line that starts with Uid:. From the uid, you can derive the username with pwd.getpwuid(pid).pw_name.

UID   = 1
EUID  = 2

def owner(pid):
    '''Return username of UID of process pid'''
    for ln in open('/proc/%d/status' % pid):
        if ln.startswith('Uid:'):
            uid = int(ln.split()[UID])
            return pwd.getpwuid(uid).pw_name

(The constants are derived from fs/proc/array.c in the Linux kernel.)

Upvotes: 11

c-ram
c-ram

Reputation: 154

you could use subprocess.Popen to invoke a shell command, and read from the stdout to a variable.

python subprocess

import subprocess
p=Popen(['/bin/ps', '-o', 'comm,pid,user',stdout=PIPE)
text=p.stdout.read()

Upvotes: 2

MarcoS
MarcoS

Reputation: 13574

In Linux, you may do ps -f and you get the UID and PID (-f does full-format listing).

Upvotes: 0

Related Questions