96

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

msw
  • 42,753
  • 9
  • 87
  • 112
Madzombie
  • 961
  • 1
  • 6
  • 3

7 Answers7

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
Daniel F
  • 13,684
  • 11
  • 87
  • 116
bobince
  • 528,062
  • 107
  • 651
  • 834
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]
phoenix
  • 7,988
  • 6
  • 39
  • 45
enthus1ast
  • 2,099
  • 15
  • 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.

Matt
  • 1,841
  • 2
  • 25
  • 30
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.

ars
  • 120,335
  • 23
  • 147
  • 134
  • 3
    PSI was last updated in 2009, whereas psutil was updated this month (Nov 2015) - seems like psutil is a better bet. – RichVel Nov 07 '15 at 07: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).

Community
  • 1
  • 1
extraneon
  • 23,575
  • 2
  • 47
  • 51
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'))
HADI AMAN
  • 9
  • 2
  • 1
    Welcome to StackOverflow. While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) 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](https://stackoverflow.com/posts/64906644/edit) your answer to add explanations and give an indication of what limitations and assumptions apply. – Ruli Nov 19 '20 at 07:45
  • This code is poorly written, needlessly complex, and unpythonic. It is not a good example of how to achieve this. – Brandon Feb 22 '23 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])
Manivannan Murugavel
  • 1,476
  • 17
  • 14