您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

用python杀死进程

用python杀死进程

您可以使用以下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 2022/1/1 18:18:02 有517人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶