Process list on Linux via Python

2019-01-03 09:44发布

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

标签: python linux
6条回答
Fickle 薄情
2楼-- · 2019-01-03 10:21

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.

查看更多
够拽才男人
3楼-- · 2019-01-03 10:21

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).

查看更多
Animai°情兽
4楼-- · 2019-01-03 10:23

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.

查看更多
你好瞎i
5楼-- · 2019-01-03 10:35
import os
lst = os.popen('sudo netstat -tulpn').read()
lst = lst.split('\n')
for i in range(2,len(lst)):
    print(lst[i])
查看更多
混吃等死
6楼-- · 2019-01-03 10:42

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楼-- · 2019-01-03 10:47

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
查看更多
登录 后发表回答