我希望我的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
它不会终止旧的进程,而是现在可以运行多次。
sudo /opt/fhem/python/start.py &
但如果它运行多次,信号也会被发送多次,导致灯光闪烁。这就是为什么我正在寻找一种在启动新进程之前终止旧进程的方法。 - Martinsudo kill 1234
(1234 是 pid) 来杀死它们。 - Martinproc.stdout
中是否有任何pid
? - Dan Cornilescu