在 linux (Python) 中使用其名称杀死进程
这可行,但它会杀死每个 Python 进程。
pkill python
但是,我不能这样做:
pkill myscript.py
我也尝试过killall,但也没有运气。 我必须使用正则表达式吗?
顺便说一句,我想在 python 脚本中使用 import os. 来完成此操作。
this works, but it kills every Python process.
pkill python
However, I cannot do:
pkill myscript.py
I have also tried killall, but with no luck either.
Do I have to user regular expressions?
By the way, I want to do this in a python script with import os.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否从终止 Python 子进程的同一个脚本启动了该子进程?如果是这样,请参阅此问题了解详细信息。如果没有,您可以使用 pkill 的 -f 选项在 Python 进程的参数列表中搜索脚本名称,但您仍然面临杀死您不想要的东西的风险。有关详细信息,请参阅手册页。
Did you launch the Python subprocess from the same script you are killing it from? If so, see this question for details. If not, you can use
pkill
's -f option to search for the script name in the Python process's argument list, but you still run the risk of killing something you didn't intend to. See the man page for more info.您可以让进程将其
pid
写入文件吗?在 Python 中,你会得到这样的 pid:
按名称杀死很方便,但有时会产生意想不到的后果,正如你所看到的。
Are you able to have the process write it's
pid
to a file?In Python you get the pid like this:
Killing by name is convenient, but sometimes has undesired consequences as you have seen.
您需要查找进程 ID (pid)。您可以使用命令“ps -A | grep NAME”,然后应用“kill -9 PID”。这些命令可以很容易地翻译成Python。
尝试使用“名称”(如 pkill 中的)可能会产生多个匹配项,从而产生意外的结果(至少在问题中设置的上下文中)。
you need to lookup the process id (pid). You can use the command "ps -A | grep NAME" and then apply "kill -9 PID". These commands can easily be translated to python.
Trying to use a "name" (as in pkill) can yield multiple matches and thus unexpected results (at least in the context set above in the question).
sudo Kill -9 `pgrep python`
该命令将杀死所有正在运行的 python 进程
sudo kill -9 `pgrep python`
This command will kill all the running python processes
试试这个:
当然,您必须更改代码才能终止名为“myscript”的进程
在 UNIX 系统上,可执行文件在开头包含几个字节,告诉操作系统正在使用什么二进制格式。如果前两个字节是
#!
,则操作系统假定这实际上是一个可以由另一个程序执行的文本文件,并且操作系统加载另一个程序并将文本文件传递给它。在这种情况下,我可能可以在顶行写上
#!/usr/bin/python
,但如果你的 python 位于/usr/local/bin
中,那么它行不通。相反,我利用env
让它在您的正常路径中搜索 python。所有 UNIX 系统的 /usr/bin 中都有 env。要了解更多信息,您可以输入man env
。Try this:
Of course you will have to change the code to kill a process named "myscript"
On UNIX systems, an executable file contains a few bytes at the beginning which tell the OS what binary format is being used. If the first two bytes are
#!
then the OS assumes that this is actually a text file which can be executed by another program, and the OS loads the other program and passes to it, the text file.In this case I probably could have written
#!/usr/bin/python
on the top line, but if your python is in/usr/local/bin
, then it would not work. Instead, I leverageenv
to get it to search your normal path for python. All UNIX systems have env in /usr/bin. For a bit more info you can type inman env
.