how do I get the process list in Python?

我的梦境 提交于 2019-11-27 16:40:25

问题


How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.


回答1:


On linux, the easiest solution is probably to use the external ps command:

>>> import os
>>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
...        for x in os.popen('ps h -eo pid:1,command')]]

On other systems you might have to change the options to ps.

Still, you might want to run man on pgrep and pkill.




回答2:


On Linux, with a suitably recent Python which includes the subprocess module:

from subprocess import Popen, PIPE

process = Popen(['ps', '-eo' ,'pid,args'], stdout=PIPE, stderr=PIPE)
stdout, notused = process.communicate()
for line in stdout.splitlines():
    pid, cmdline = line.split(' ', 1)
    #Do whatever filtering and processing is needed

You may need to tweak the ps command slightly depending on your exact needs.




回答3:


The right portable solution in Python is using psutil. You have different APIs to interact with PIDs:

>>> import psutil
>>> psutil.pids()
[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
>>> psutil.pid_exists(32498)
True
>>> p = psutil.Process(32498)
>>> p.name()
'python'
>>> p.cmdline()
['python', 'script.py']
>>> p.terminate()
>>> p.wait()

...and if you want to "search and kill":

for p in psutil.process_iter():
    if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
        p.terminate()
        p.wait()



回答4:


Why Python?
You can directly use killall on the process name.



来源:https://stackoverflow.com/questions/1091327/how-do-i-get-the-process-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!