用Python终止进程

9 投票
2 回答
40070 浏览
提问于 2025-04-16 07:16

我需要写一个脚本,让用户输入以下内容:

1) 进程名称(在Linux系统上)。

2) 这个进程写入的日志文件名称。

这个脚本需要先结束这个进程,并确认它已经停止运行。

然后,把日志文件的名称改成一个新的文件名,文件名里要包含时间和日期。

最后,再重新启动这个进程,并确认它已经正常运行,这样它才能继续写入日志文件。

提前感谢大家的帮助。

2 个回答

2

如果你知道怎么在终端里操作,那你可以使用下面的命令:

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

这样你就可以在Python里面写一个类似小脚本的东西。我也建议你可以把这个脚本单独写出来,然后在Python里调用它:

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

祝好运!

22

你可以通过使用 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.

希望这能帮到你

撰写回答