按名称杀死过程?(Kill process by name?)

编程入门 行业动态 更新时间:2024-10-16 00:19:45
名称杀死过程?(Kill process by name?)

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

ps -A | grep iChat

然后:

kill -9 PID

但是,我不太清楚如何将这些命令翻译成Python。

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

ps -A | grep iChat

Then:

kill -9 PID

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

最满意答案

假设你在一个类Unix平台上(所以ps -A存在),

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

给出你在out变量(一个字符串)中的ps -A输出。 你可以把它分成几行,并循环在他们的...:

>>> 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 ,但我不是特别喜欢这种风格,所以我宁愿使用这个命名的常量)。

当然,您可以对这些行进行更加复杂的处理,但这会模拟您在shell中的工作。

如果你以后是避免ps ,那么很难在不同的类Unix系统之间进行操作( ps是他们在某种意义上获得进程列表的通用API)。 但是,如果你有一个特定的类Unix系统,只有(不需要任何跨平台的可移植性),这可能是可能的; 特别是在Linux上, /proc伪文件系统是非常有帮助的。 但是,在我们可以帮助下一部分之前,您需要澄清您的具体要求。

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

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

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

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

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.

更多推荐

本文发布于:2023-07-15 17:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1116639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   过程   process   Kill

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!