gpt4 book ai didi

python - 用python杀死进程

转载 作者:IT王子 更新时间:2023-10-29 00:16:41 26 4
gpt4 key购买 nike

我需要制作一个脚本,从用户那里获取以下内容:

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

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

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

在此先感谢您的帮助。

最佳答案

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

希望对你有帮助

关于python - 用python杀死进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com