小编Mar*_*tin的帖子

检查Python脚本是否已在运行

我希望我的Python脚本检查,如果它已经运行,如果是,则杀死旧进程.我试过这个,但它确实不起作用......

import os
import subprocess
import signal

process_name = "python " + os.path.abspath(__file__)
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
Run Code Online (Sandbox Code Playgroud)

它不会杀死旧进程并且现在运行多次.

python linux kill process

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

kill ×1

linux ×1

process ×1

python ×1