错误:在python中赋值之前引用了局部变量

2024-10-01 09:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pythonwebsocket客户端代码

run_once1 = True
run_once2 = False

def on_message(ws, message):

    if 'Temp' in message:
        if run_once1 is True:
            #Run this code once
            print("Temp is present")
            run_once1 = False
            run_once2 = True

    else:
        if run_once2 is True:
            #Run this code once
            print("Temp is not present")     
            run_once1 = True
            run_once2 = False       

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("CLOSE ")

def on_open(ws):
    print("OPEN")
    msg = "<MESSAGE>"
    ws.send(msg)

ws = websocket.WebSocketApp(URL, on_message= on_message, on_error=on_error, on_close=on_close)
ws.on_open = on_open
ws.run_forever()

所以在上面的代码中,我打开了一个websocket,然后每当我收到新消息时,on_message()函数就会被调用。在这个函数中,我在消息中寻找标记Temp。如果它存在,我只想打印它并运行一次。接下来,当Temp不存在时,我想打印它并只运行一次该代码。但是上面的代码给出了错误:

error from callback <function on_message at 0x000001D35366D840>: local variable 'run_once1' referenced before assignment

error from callback <function on_message at 0x000001D35366D840>: local variable 'run_once2' referenced before assignment

我应该把这些变量写在哪里,这样它就不会给我这个错误了。在

谢谢


Tags: run代码falsetruemessageifwsis
2条回答

变量被声明在函数的作用域之外,也就是说,你的函数看不到你在它的缩进之外声明的变量(或者在函数内部声明的变量也不会改变外部相同命名变量的值)。在

您需要做的是将这些变量作为函数参数传递,例如:

run_once1 = True 
run_once2 = False

def on_message(ws, message, run_once1, run_once2):

    if 'Temp' in message:
        if run_once1 is True:
            #Run this code once
            print("Temp is present")
            run_once1 = False
            run_once2 = True

    else:
        if run_once2 is True:
            #Run this code once
            print("Temp is not present")     
            run_once1 = True
            run_once2 = False       
    return run_once1, run_once2

run_once1, run_once2 = on_message (ws, message, run_once1=run_once1, run_once2=run_once2

但是,在您的情况下,它不起作用,因为您希望直接调用这个函数。然后,为了保持状态,我会将“on_message”写成类:

^{2}$

为了分配给函数内的全局变量,需要在该函数中将其声明为全局变量。例如:

def on_message(ws, message):
    global run_once1
    global run_once2

    # remainder of function as before

相关问题 更多 >