用python杀死进程

时间:2010-11-18 12:35:19

标签: python linux process kill

我需要创建一个从用户那里得到以下内容的脚本:

1)进程名称(在linux上)。

2)此进程写入的日志文件名。

它需要终止进程并验证进程是否已关闭。 使用时间和日期将日志文件名更改为新文件名。 然后再次运行该过程,验证它是否正常,以便它继续写入日志文件。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:18)

您可以使用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.

希望这可以提供帮助

答案 1 :(得分:2)

如果您知道如何在终端中执行此操作,则可以使用以下内容:

import os
os.system("your_command_here; second_command; third; etc")

所以你最终在python中有了一些迷你shell脚本。我还会考虑让这个shell脚本独立存在,然后从python中调用它:

import os
os.system("path/to/my_script.sh")

干杯!