Linux 用python杀死进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4214773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
kill process with python
提问by Bar Aviv
I need to make a script that gets from the user the following:
我需要制作一个从用户那里获取以下信息的脚本:
1) Process name (on linux).
1) 进程名称(在 linux 上)。
2) The log file name that this process write to it.
2) 此进程写入的日志文件名。
It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then run the process again, verify that it's up in order it will continue to write to the log file.
它需要终止进程并验证进程是否已关闭。将日志文件名更改为带有时间和日期的新文件名。然后再次运行该进程,验证它是否已启动,以便继续写入日志文件。
Thanks in advance for the help.
在此先感谢您的帮助。
采纳答案by mouad
You can retrieve the process id (PID) given it name using pgrep
command like this:
您可以使用如下pgrep
命令检索给定名称的进程 ID (PID) :
import subprocess
import signal
import os
from datetime import datetime as dt
process_name = sys.argv[1]
log_file_name = sys.argv[2]
proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)
# Kill process.
for pid in proc.stdout:
os.kill(int(pid), signal.SIGTERM)
# Check if the process that we killed is alive.
try:
os.kill(int(pid), 0)
raise Exception("""wasn't able to kill the process
HINT:use signal.SIGKILL or signal.SIGABORT""")
except OSError as ex:
continue
# Save old logging file and create a new one.
os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))
# Empty the logging file.
with open(log_file_name, "w") as f:
pass
# Run the process again.
os.sytsem("<command to run the process>")
# you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.
# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again.
Hope this can help
希望这可以帮助
回答by Morlock
If you know how to do it in the terminal, then you could use the following:
如果您知道如何在终端中执行此操作,则可以使用以下命令:
import os
os.system("your_command_here; second_command; third; etc")
So that you end up having sort of a mini shell script inside python. I would also consider making this shell script exist on its own and then call it from python:
这样你最终会在 python 中拥有一个迷你 shell 脚本。我也会考虑让这个 shell 脚本独立存在,然后从 python 调用它:
import os
os.system("path/to/my_script.sh")
Cheers!
干杯!