python - 检查 Python 脚本是否已经在运行

标签 python linux process kill

我想让我的 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/

相关文章:

linux - 当从 ls | 传送结果时 head 不起作用grep

java - 从 Java 应用程序以其他用户权限运行新进程

linux - ./在 linux 中的命令名称是什么?

php - 获取特定运行的 PHP 脚本的 CPU 使用率

python - 从列表中仅获取所需的字符串

python - 重命名子图中的图例 : matplotlib

linux - 如何在linux中删除许多0字节的文件?

linux - 背页社区版 (Sharelatex) |如何从磁盘读取更改后的 LaTex 文件?

python - 在 Sqlalchemy 查询中忽略 MYSQL 数据库中的锁

python - Bokeh 上是否提供图表的水平滚动条?