开发者

Kill the process using its name inside linux (Python)

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.


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.


Are you able to have the process write it's pid to a file?
In Python you get the pid like this:

import os
os.getpid()

Killing by name is convenient, but sometimes has undesired consequences as you have seen.


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`

This command will kill all the running python processes


Try this:

echo '#!/usr/bin/env python' > myscript
cat myscript.py >>myscript
chmod +x myscript
./myscript

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 leverage env 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 in man env.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜