3

I know it has something to do with /proc but I'm not really familiar with it.

PetitPlaid
  • 91
  • 3
  • 8

6 Answers6

1

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]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0
import subprocess

ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE)
print ps.stdout.readlines()
0

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

guettli
  • 25,042
  • 81
  • 346
  • 663
dgsleeps
  • 700
  • 6
  • 7
0

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))
nillu
  • 585
  • 4
  • 15
0

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
    
AngeloAD
  • 101
  • 3
-2

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