我试图杀死一个进程(特别是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 iChatThen:
kill -9 PIDHowever, 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.
更多推荐
发布评论