This script should tell me if another python file is running or not running and prints file on/file off every time the file stops/starts running:
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')
The error:
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
I am using vs code by the way.
The line status = False
is a global variable assignment in a function, and therefore there must be a global
declaration at the start of the function: 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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.