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

Python检测进程运行状态遇UnboundLocalError及Pylance问题求助

Python进程检测脚本异常修复

问题背景

需要实现的脚本功能:

  • 检测指定Python文件是否处于运行状态
  • 目标文件启动时打印file on
  • 目标文件停止运行时打印file off
    开发环境为VS Code,编码后遇到两个异常:
  1. Pylance提示代码中status_1变量未被访问
  2. 脚本运行时抛出UnboundLocalError: local variable 'status' referenced before assignment异常

原始代码

import psutil
import os
status = True
status_1 = True
while True:
    def is_running(script):
        for q in psutil.process_iter():
            if q.name().startswith('python'):
                if len(q.cmdline())>1 and script in q.cmdline()[1] and q.pid !=os.getpid():
                    if status:
                        status_1 = True #"status_1" is not accessed by Pylance
                        status = False
                        print('file on')
    if not is_running("test.py"):
        if status_1:
            status = True
            status_1 = False
            print('file off')

报错信息

Traceback (most recent call last):
  File "c:\Users\Win10\file.py", line 27, in <module>
    if not is_running("test.py"):
  File "c:\Users\Win10\file.py", line 23, in is_running
    if status:
UnboundLocalError: local variable 'status' referenced before assignment

问题根因

  • 作用域错误触发UnboundLocalError:Python函数内部如果存在对变量的赋值操作,会默认将该变量识别为函数内局部变量,不会自动读取全局作用域的status、status_1。执行if status:判断时,局部变量status尚未赋值就被调用,直接抛出异常。
  • Pylance提示status_1未访问:is_running函数被定义在while True死循环内部,每次循环都会重复定义该函数;且函数内赋值的status_1是函数局部变量,和外层全局的status_1完全隔离,该局部变量赋值后没有任何读取操作,因此被Pylance标记为未访问。
  • 逻辑缺陷:原is_running函数没有显式返回值,即使遍历到运行中的目标脚本也不会返回True,外层if not is_running(...)判断永远成立,状态检测逻辑完全失效。

修复方案

修复要点:

  • 将is_running函数移到循环外部,避免每次循环重复定义函数
  • 拆分函数职责:is_running只负责返回进程是否运行的布尔值,状态更新、打印逻辑统一放在主循环处理,从根源上避免全局变量作用域冲突
  • 增加进程遍历的异常捕获,处理权限不足、进程中途退出的场景,避免脚本崩溃
  • 增加轮询间隔,降低CPU占用

修复后可直接运行的代码:

import psutil
import os
import time

# 状态标记:记录上一次检测时目标脚本是否处于运行状态,避免重复打印提示
is_file_running = False

def is_running(script):
    for proc in psutil.process_iter():
        try:
            if proc.name().startswith('python'):
                cmdline = proc.cmdline()
                # 排除检测脚本自身进程,匹配目标脚本名
                if len(cmdline) > 1 and script in cmdline[1] and proc.pid != os.getpid():
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            # 跳过已退出、无权限访问的进程
            continue
    return False

if __name__ == "__main__":
    while True:
        current_status = is_running("test.py")
        # 状态从停止切到运行
        if current_status and not is_file_running:
            print("file on")
            is_file_running = True
        # 状态从运行切到停止
        if not current_status and is_file_running:
            print("file off")
            is_file_running = False
        # 1秒检测一次,避免CPU空转占用过高
        time.sleep(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 08:09:15