0

我正在编写一个脚本来在用户每次按键时输入一些内容。我最终不得不在监听器之前定义一个全局变量并从监听器中引用它,尽管事先明确定义了它,但我得到了一个 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 上运行

4

1 回答 1

0

您正在访问尚未初始化的函数内的全局声明变量,因为 pynput 的键盘侦听器被处理为 Thread 并且具有不同的 scope。因此,您必须在访问之前将该变量指定为全局变量。

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
于 2018-07-18T14:13:27.177 回答