Joh*_*son 7 python unix kill ps processlist
如何从Unix获取所有正在运行的进程的进程列表,包含命令/进程名称和进程ID,因此我可以过滤和终止进程.
在Linux上,使用适当的最新Python包含subprocess模块:
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
Run Code Online (Sandbox Code Playgroud)
您可能需要根据具体需要稍微调整ps命令.
Python中正确的可移植解决方案是使用psutil.您有不同的API与PID交互:
>>> 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()
Run Code Online (Sandbox Code Playgroud)
......如果你想"搜索并杀死":
for p in psutil.process_iter():
if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
p.terminate()
p.wait()
Run Code Online (Sandbox Code Playgroud)
在 Linux 上,最简单的解决方案可能是使用外部ps命令:
>>> 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')]]
Run Code Online (Sandbox Code Playgroud)
在其他系统上,您可能必须将选项更改为ps.
不过,您可能想man在pgrep和 上运行pkill。
| 归档时间: |
|
| 查看次数: |
14315 次 |
| 最近记录: |