How can I get running process list using Python on Linux?
7 Answers
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
-
13You 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 05 '12 at 21:37
-
4At last! Validation! Now I can stop! :-) – bobince Nov 11 '12 at 01:38
-
6-1 for /proc since its not portable and there are better interfaces available – Good Person Oct 17 '14 at 21:05
-
2Watch out: the command line is terminated by 0x00. Whitespaces are also replaced with the same character. – Federico Mar 26 '15 at 19:36
-
2Just 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 07 '15 at 07:18
-
1Everything in Linux is a file. I think reading from proc is the best way. – Ahmed Sep 30 '16 at 19:16
-
1You forgot about close()! – PADYMKO Dec 22 '16 at 18:47
-
OSError: [Errno 2] No such file or directory: '/proc' – ishandutta2007 Jun 11 '17 at 16:33
-
I think it's the best answer for this question. And "portability" is not needed - question about linux only – Alex Yu May 19 '18 at 17:47
-
For fun, a oneliner that seems to work in python3.5 and up. I'll let you know when it fails: `pidmap = {p.parent.name: b' '.join(p.read_bytes().strip(b'\0').split(b'\0')).decode('ascii') for p in pathlib.Path('/proc').glob('*/cmdline')}` – kojiro Oct 30 '19 at 21:54
-
@PADYMKO: Or rather, forgot about `with`. – Martin Ueding May 03 '21 at 07:45
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]

- 7,988
- 6
- 39
- 45

- 2,099
- 15
- 22
-
3just take a look at the [documentation](http://code.google.com/p/psutil/wiki/Documentation). – enthus1ast Aug 04 '12 at 09:57
-
-
6It's not completely platform independent -- on OSX you can run into AccessDenied errors: https://groups.google.com/forum/?fromgroups=#!topic/psutil/bsjpawhiWms – amos Mar 27 '13 at 00: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 '14 at 20:24
-
To amplify the OSX point - you need root privileges on OSX to get process info, unlike Linux. – RichVel Nov 07 '15 at 07:22
-
And it is available as python-psutil from epel for fedora/centos/rhel family. – BartBiczBoży Dec 31 '16 at 07:36
-
-
I've had trouble with this: I start a dummy process, then look through all the processes for one with the name `dummy_process` and I can't see it. If I call `ps -u` then I can see my process. What am I doing wrong? – R.Mckemey Aug 22 '18 at 10:47
-
@enthus1ast your link seems down, new docs seem to be here: https://psutil.readthedocs.io/en/latest/ – Арсений Пичугин Dec 04 '18 at 14:48
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.

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

- 120,335
- 23
- 147
- 134
-
3PSI 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
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).
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'))

- 9
- 2
-
1Welcome 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
import os
lst = os.popen('sudo netstat -tulpn').read()
lst = lst.split('\n')
for i in range(2,len(lst)):
print(lst[i])

- 1,476
- 17
- 14