我想让我的 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
它不会终止旧进程并且现在运行多次。
原文由 Martin 发布,翻译遵循 CC BY-SA 4.0 许可协议
我当前的解决方案看起来像这样(在 OSX 上)。我将 pgrep 与 regexp 结合使用
据我测试,即使 python 字符串不同,这也应该有效。脚本的位置也无关紧要