开发者

Making a key-command for a python program with no GUI

开发者 https://www.devze.com 2023-01-10 17:22 出处:网络
I want to make a key command so that the program will stop running when the Ctrl key then the \'e\' key then the \'x\' key then the \'i\' and \'t\' keys are hit. So basically when the program is runni

I want to make a key command so that the program will stop running when the Ctrl key then the 'e' key then the 'x' key then the 'i' and 't' keys are hit. So basically when the program is running if you type Ctrl + exit, the program will stop running. There is no GUI and I don't want to do this via a python interpreter.

The end goal is a program that will close if the Ctrl + exit command is typed, regardless of what other programs are in focus. This program is going to be a light weight key-logger, so having a GUI would be pointles开发者_运维百科s.


Use a simple FSM for the "exiting logic" while you're logging the received keys, e.g.:

FINAL_STATE = 9999
transitions = {(None, 'e'): 1, (1, 'x'): 2, (2, 'i'): 3, (3, 't'): FINAL_STATE}

def keylogger_logic(filename, get_next_keystroke, fsm_state=None):
    with open(filename, 'w') as f:
        k = get_next_keystroke()
        f.write(k)
        f.flush()
        fsm_state = transitions.get((fsm_state, k))
        if fsm_state == FINAL_STATE: break

This assume you have or write a function that returns "the next keystroke" as a string, and pass it to keylogger_logic as the second argument (I'd do it this way, not by hardcoding the key-getter functionality together with this logic, as an application of the Dependency Injection pattern to make things very easy to unit-test; similarly for having fsm_state as an argument, i.e., making it settable by the caller -- eases testing). Easy to adjust if you'd rather have your "get next keystroke" function return things other than a string (you'll just have to fix the f.write and the transitions table).

0

精彩评论

暂无评论...
验证码 换一张
取 消