未声明的局部变量 - 无法用任何当前堆栈解决方案修复
Local variable not declared - cannot be fixed with any current stack solutions
我知道这是一个在这里被问过多次的问题,但即使在查看并尝试使用本网站上的所有解决方案后,none 也解决了我的问题。这是我的代码:
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()
我在 运行 这个循环中得到的错误是:
Task exception was never retrieved
future: .print_events() done, defined at etho.py:113> exception=UnboundLocalError("local variable 'a' referenced before assignment",)>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "etho.py", line 124, in print_events
if x += 1:
UnboundLocalError: local variable 'x' referenced before assignment
无论我在哪里分配变量或声明它,当我尝试在 if 语句中使用它或添加到它时它都会抛出错误,但当我只是将它设置为一个数字时不会抛出错误。我认为这与它所在的怪异循环有关。
print_events
将 x
和 y
视为自身的局部变量,因为它们在函数内部被修改并且未在函数内部声明为全局变量。既然要修改,就需要在print_events
:
里面加上declare them global
async def print_events(device):
global x, y
async for event in device.async_read_loop():
...
请注意,将它们作为参数传递将不起作用,因为您想在函数内修改它们并在函数外访问修改后的值。
我知道这是一个在这里被问过多次的问题,但即使在查看并尝试使用本网站上的所有解决方案后,none 也解决了我的问题。这是我的代码:
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()
我在 运行 这个循环中得到的错误是:
Task exception was never retrieved future: .print_events() done, defined at etho.py:113> exception=UnboundLocalError("local variable 'a' referenced before assignment",)>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "etho.py", line 124, in print_events
if x += 1:
UnboundLocalError: local variable 'x' referenced before assignment
无论我在哪里分配变量或声明它,当我尝试在 if 语句中使用它或添加到它时它都会抛出错误,但当我只是将它设置为一个数字时不会抛出错误。我认为这与它所在的怪异循环有关。
print_events
将 x
和 y
视为自身的局部变量,因为它们在函数内部被修改并且未在函数内部声明为全局变量。既然要修改,就需要在print_events
:
async def print_events(device):
global x, y
async for event in device.async_read_loop():
...
请注意,将它们作为参数传递将不起作用,因为您想在函数内修改它们并在函数外访问修改后的值。