Process list on Linux via Python
How can I get run开发者_开发问答ning process list using Python on Linux?
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
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]
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.
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.
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'))
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).
import os
lst = os.popen('sudo netstat -tulpn').read()
lst = lst.split('\n')
for i in range(2,len(lst)):
print(lst[i])
精彩评论