gpt4 book ai didi

python - UnboundLocalError 继续弹出,我不明白为什么

转载 作者:行者123 更新时间:2023-12-01 00:28:26 25 4
gpt4 key购买 nike

终端输出错误,指出赋值前引用了局部变量“Listener”。我正在尝试导入监听器 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

最佳答案

问题在于您在 _keylogger 中重新定义了 Listener。有关说明,请参阅 Why am I getting an UnboundLocalError when the variable has a value?在 Python 常见问题解答中,或 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com