简体   繁体   中英

pynput UnboundLocalError when referencing global variable from inside listener

I'm writing a script to type something every time a user presses a key. I ended up having to define a global variable before the listener and reference it from within the listener and I got an UnboundLocalError despite clearly defining it beforehand. here is the code:

import pynput

controller = pynput.keyboard.Controller()
is_typing = False
def on_press(key):
    if not is_typing:
        is_typing = True
        controller.type('test')
        is_typing = False

with pynput.keyboard.Listener(on_press=on_press) as listener:
    listener.join()

After pressing a key while the script is running, I get this error:

Traceback (most recent call last):
  File ".\typer.py", line 12, in <module>
    listener.join()
  File "C:\Python35\lib\site-packages\pynput\_util\__init__.py", line 199, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\Python35\lib\site-packages\six.py", line 692, in reraise
    raise value.with_traceback(tb)
  File "C:\Python35\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
    return f(self, *args, **kwargs)
  File "C:\Python35\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
    self.on_press(key)
  File "C:\Python35\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
    if f(*args) is False:
  File ".\typer.py", line 6, in on_press
    if not is_typing:
UnboundLocalError: local variable 'is_typing' referenced before assignment

I'm running on windows 10, python 3.5.2, and pynput 1.4

You're accessing a globally declared variable inside a function where it is not initialized yet, because pynput's keyboard listener is handled as a Thread and has different scope . So, you'll have to specify the variable as a global variable before accessing it.

def on_press(key):
 # global is_typing
 print globals()
 global is_typing
 if not is_typing:
    is_typing = True
    controller.type('test')
    is_typing = False

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM