Pylance 无法访问"UnboundLocalError: local variable 'status' referenced before assignment"和"status_1"



这个脚本应该告诉我另一个python文件是否正在运行,并在每次文件停止/开始运行时打开/关闭文件:

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:UsersWin10file.py", line 27, in <module>
if not is_running("test.py"):
File "c:UsersWin10file.py", line 23, in is_running
if status:
UnboundLocalError: local variable 'status' referenced before assignment

顺便说一下,我正在使用vs代码。

status = False是函数中的全局变量赋值,因此函数开头必须有一个global声明:global status

def is_running(script):
global status
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')

相关内容

最新更新