96

How can I get running process list using Python on Linux?

0

7 Answers 7

131

IMO looking at the /proc filesystem is less nasty than hacking the text output of ps.

import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]

for pid in pids:
    try:
        print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('\0')
    except IOError: # proc has already terminated
        continue
11
  • 13
    You will have to surround the read() call with a try/except block as a pid returned from reading os.listdir('/proc') may no longer exist by the time you read the cmdline.
    – Yanamon
    Sep 5, 2012 at 21:37
  • 4
    At last! Validation! Now I can stop! :-)
    – bobince
    Nov 11, 2012 at 1:38
  • 6
    -1 for /proc since its not portable and there are better interfaces available Oct 17, 2014 at 21:05
  • 2
    Watch out: the command line is terminated by 0x00. Whitespaces are also replaced with the same character.
    – Federico
    Mar 26, 2015 at 19:36
  • 2
    Just use psutil - it does all this through a nice Pythonic interface and is portable if you ever want to run on a non-Linux server.
    – RichVel
    Nov 7, 2015 at 7:18
89

You could use psutil as a platform independent solution!

import psutil
psutil.pids()

[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235, 
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
9
  • 3
    just take a look at the documentation.
    – enthus1ast
    Aug 4, 2012 at 9:57
  • Thanks for bringing this up! Neat package.
    – codekoala
    Nov 6, 2012 at 15:49
  • 6
    It's not completely platform independent -- on OSX you can run into AccessDenied errors: groups.google.com/forum/?fromgroups=#!topic/psutil/bsjpawhiWms
    – amos
    Mar 27, 2013 at 0:22
  • @amos kinda makes sense - you'd want to have privileges in place first before reaching out to information about processes. Thanks for the hint.
    – JSmyth
    Jan 16, 2014 at 20:24
  • To amplify the OSX point - you need root privileges on OSX to get process info, unlike Linux.
    – RichVel
    Nov 7, 2015 at 7:22
8

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

7

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

1
  • 3
    PSI was last updated in 2009, whereas psutil was updated this month (Nov 2015) - seems like psutil is a better bet.
    – RichVel
    Nov 7, 2015 at 7:17
0

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

0
from psutil import process_iter
from termcolor import colored

names = []
ids = []

x = 0
z = 0
k = 0
for proc in process_iter():
    name = proc.name()
    y = len(name)
    if y>x:
        x = y
    if y<x:
        k = y
    id = proc.pid
    names.insert(z, name)
    ids.insert(z, id)
    z += 1

print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
    z = x
    print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))
2
  • 1
    Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Ruli
    Nov 19, 2020 at 7:45
  • This code is poorly written, needlessly complex, and unpythonic. It is not a good example of how to achieve this.
    – Brandon
    Feb 22 at 19:31
-2
import os
lst = os.popen('sudo netstat -tulpn').read()
lst = lst.split('\n')
for i in range(2,len(lst)):
    print(lst[i])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.