You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测指定Python脚本EXIF_GUI_EXPERIMENT.py是否在运行?

检测Python脚本运行状态的最佳方法

你的脚本没返回结果是因为pgrep默认匹配的是进程名(这里是python3),而不是命令行参数里的脚本文件名。以下是几种可靠的检测方法:

方法1:用pgrep匹配命令行参数

直接用pgrep的-f选项,它会匹配整个命令行内容,而非只看进程名,同时避免shell=True的安全风险:

#!/usr/bin/python3
import subprocess

cmd = ["pgrep", "-f", "EXIF_GUI_EXPERIMENT.py"]
result = subprocess.run(cmd, capture_output=True, text=True)

# 判断运行状态:stdout有内容则表示进程存在
if result.stdout.strip():
    print("脚本正在运行")
else:
    print("脚本未运行")

方法2:用ps结合grep过滤

如果习惯用ps命令,可直接过滤命令行中的脚本名,注意排除grep自身进程:

#!/usr/bin/python3
import subprocess

cmd = "ps -fA | grep EXIF_GUI_EXPERIMENT.py | grep -v grep"
result = subprocess.run(cmd, capture_output=True, text=True, shell=True)

if result.stdout.strip():
    print("脚本正在运行")
else:
    print("脚本未运行")

方法3:读取/proc目录(高效无外部依赖)

Linux系统的/proc目录存储着所有进程的详细信息,可直接遍历进程的cmdline文件匹配脚本名,无需调用外部命令:

#!/usr/bin/python3
import os

script_name = "EXIF_GUI_EXPERIMENT.py"
running = False

for pid in os.listdir("/proc"):
    if pid.isdigit():
        try:
            with open(f"/proc/{pid}/cmdline", "rb") as f:
                # 进程cmdline用\x00分隔,替换为空格后匹配
                cmdline = f.read().decode().replace("\x00", " ")
                if script_name in cmdline:
                    running = True
                    break
        except (PermissionError, FileNotFoundError):
            continue

print("脚本正在运行" if running else "脚本未运行")

内容的提问来源于stack exchange,提问作者bob_the_bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:19:53