按名称杀死进程? [英] Kill process by name?

查看:88
本文介绍了按名称杀死进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图杀死一个进程(特别是iChat).在命令行上,我使用以下命令:

I'm trying to kill a process (specifically iChat). On the command line, I use these commands:

ps -A | grep iChat 

然后:

kill -9 PID

但是,我不确定如何将这些命令转换为Python.

However, I'm not exactly sure how to translate these commands over to Python.

推荐答案

假设您使用的是类似Unix的平台(因此存在ps -A),

Assuming you're on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

out变量(字符串)中提供ps -A的输出.您可以将其分解成几行然后循环播放...:

gives you ps -A's output in the out variable (a string). You can break it down into lines and loop on them...:

>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

(您可以避免导入signal,而使用9而不是signal.SIGKILL,但我只是不太喜欢这种样式,所以我宁愿以这种方式使用命名常量).

(you could avoid importing signal, and use 9 instead of signal.SIGKILL, but I just don't particularly like that style, so I'd rather used the named constant this way).

当然,您可以在这些行上进行更复杂的处理,但这模仿了您在shell中所做的事情.

Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.

如果您要避免使用ps,那么在不同的类似Unix的系统上很难做到这一点(从某种意义上说,ps是获取进程列表的通用API).但是,如果只考虑特定的类Unix系统(不需要任何跨平台可移植性),则可能是可行的.特别是在Linux上,/proc伪文件系统非常有用.但是您需要澄清您的确切要求,然后我们才能为后一部分提供帮助.

If what you're after is avoiding ps, that's hard to do across different Unix-like systems (ps is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.

这篇关于按名称杀死进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆