我想让我的 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
它不会终止旧进程,现在会运行多次。
最佳答案
我当前的解决方案如下所示(在 OSX 上)。 我将 pgrep 与正则表达式结合使用
import subprocess
cmd = ['pgrep -f .*python.*testing03.py']
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
my_pid, err = process.communicate()
if len(my_pid.splitlines()) >0:
print("Running")
exit()
else:
print("Not Running")
据我测试,即使 python 字符串不同,这也应该有效。脚本的位置也不重要
关于python - 检查 Python 脚本是否已经在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799192/