我正在编写一个脚本来在用户每次按键时输入一些内容。我最终不得不在监听器之前定义一个全局变量并从监听器中引用它,尽管事先明确定义了它,但我得到了一个 UnboundLocalError 。这是代码:
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()
在脚本运行时按一个键后,我收到此错误:
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
我在 Windows 10、python 3.5.2 和 pynput 1.4 上运行