I know it has something to do with /proc but I'm not really familiar with it.
-
check this site: http://stackoverflow.com/questions/2703640/process-list-on-linux-via-python – dgsleeps Feb 27 '15 at 02:19
6 Answers
A textbook answer would be to use psutil
module like this:
import psutil,getpass,os
user_name = getpass.getuser()
process_dict = {proc.pid:proc.name() for proc in psutil.process_iter() if proc.username() == user_name}
That generates a dictionary with process id as key, and process name as value for current user processes.
That approach looks good but on my Windows server machine (where I don't have admin privileges) I couldn't get proc.username()
without getting psutil.AccessDenied
exception. So I tried to catch the exception in an helper routine, which led me to another strange error, so I dropped the whole idea and built a Windows-only solution based on tasklist
command:
tasklist /FI "USERNAME eq %USERNAME%" /FO CSV
which, adapted to python and with the same convenient pid => username dictionary format translates as:
import csv,subprocess
def get_current_user_processes():
csv_output = subprocess.check_output(["tasklist","/FI","USERNAME eq {}".format(os.getenv("USERNAME")),"/FO","CSV"]).decode("ascii","ignore")
cr = csv.reader(csv_output.splitlines())
next(cr) # skip title lines
return {int(row[1]):row[0] for row in cr}
It tells tasklist
to keep only current user processes, and to use csv output format so it can be parsed easily with the csv
module. Then, we keep only the 2 first columns (name & pid) and convert pid to integer for good measure.
It creates dictionaries like this:
{7808: 'conhost.exe', 12676: 'dwm.exe', 10120: 'ssonsvr.exe', 7052: 'tasklist.exe', 17028: 'ccshelserver.exe', 14876: 'wfcrun32.exe', 14364: 'Receiver.exe', 15024: 'conhost.exe'}
Now each individual process can be examined more deeply with psutil
without risking getting access denied or other strange errors:
d = get_current_user_processes()
processes = [proc for proc in psutil.process_iter() if proc.pid in d]

- 137,073
- 23
- 153
- 219
import subprocess
ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE)
print ps.stdout.readlines()
You can try using psutil.process_iter(). For instance:
import psutil
pids=[process.pid for process in psutil.process_iter() if
process.username == 'root']
In this case I supposed you wanted to find every process run by the "root" user
-
-
1This is VERY slow when executing on a machine that is running a large number of processes. Also, it looks like process.username is a method, so should be process.username() – Pavel Chernikov Jan 16 '18 at 18:55
-
also calling `process.username()` can throw a `psutil.AccessDenied` exception. So unable to filter that way. – Jean-François Fabre Apr 23 '18 at 09:30
I use following for such cases, check if this is helpful in your case. currently it checking for the current username, but you can costomize it.
import psutil
processes = filter(lambda p: (p.username() == os.getlogin() and (p.name() == 'python')) , psutil.process_iter())
print(list(processes))

- 585
- 4
- 15
After working with psutil for a few days, I have found that this is the best cross-platform solution:
import psutil
def iter_user_procs():
# get username of the current Python process.
# Using this instead of something like os.getlogin() avoids cross-platform issues,
# such as Windows using USERDOMAIN\USERNAME instead of just USERNAME for process owners.
username = psutil.Process.username() # get username in format used by processes
# get username from the info dict to avoid AccessDenied errors. See docs for iter_procs().
for p in psutils.iter_procs(['username']):
if p.info['username'] == username:
yield p

- 101
- 3
popen works great because you can run things through grep, cut, etc. So you can tailor the info to exactly what you want.

- 103
- 5