未声明的局部变量 - 无法使用任何当前堆栈解决方案进行修复

问题描述 投票:0回答:1

我知道这是一个问题,在这里问过几次,但即使在查看并尝试使用本网站上的所有解决方案之后,也没有解决我的问题。这是我的代码:

def trackMouse():
    global x, y
    x = 0
    y = 0
    x_max = 1000
    y_max = 1000
    keyboardEvent = evdev.InputDevice('/dev/input/event0')
    mouseEvent = evdev.InputDevice('/dev/input/event1')
    async def print_events(device):
            async for event in device.async_read_loop():
                    if event.type == ecodes.EV_REL:
                            if event.code == ecodes.REL_X:
                                    print("REL_X")
                                    x += 1
                            if event.code == ecodes.REL_Y:
                                    print("REL_Y")
                                    y += 1
                    if event.type == ecodes.EV_KEY:
                            c = categorize(event)
                            if c.keystate == c.key_down:
                                    print(c.keycode)

    for device in keyboardEvent, mouseEvent:
            asyncio.ensure_future(print_events(device))

    loop = asyncio.get_event_loop()
    loop.run_forever()

运行此循环时得到的错误是:

从未检索过任务异常:.print_events()done,定义于etho.py:113> exception = UnboundLocalError(“赋值前引用的局部变量'a'),> Traceback(最近一次调用最后一次): 文件“/usr/lib/python3.5/asyncio/tasks.py”,第239行,在_step中 result = coro.send(无) 在print_events中输入第124行的文件“etho.py” 如果x + = 1: UnboundLocalError:赋值前引用的局部变量'x'

无论我在哪里分配变量或声明它,当我尝试在if语句中使用它或添加它时会抛出错误,但不是当我只是将它设置为等于数字时。我认为它与它所处的奇怪循环有关。

python evdev
1个回答
2
投票

print_eventsxy视为本身的局部,因为它们在函数内被修改,并且在函数内部未被声明为全局。由于您要修改它们,您需要在print_events中添加声明它们全局:

async def print_events(device):
        global x, y
        async for event in device.async_read_loop():
        ...

请注意,将它们作为参数传递将不起作用,因为您要在函数内修改它们并访问函数外部的修改值。

© www.soinside.com 2019 - 2024. All rights reserved.