Python Forum

Full Version: Attempting to read keyboard outside of console
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
You know the input function? where you store a string into a variable? Yeah, I don't need that, for at least that does not benefit me.

My attempt is to read keyboard strokes without having the need of being in the console/terminal.
I want to be able to change my output when I type my keyboard, almost creating a new keyboard layout using python.
I need help on gathering keyboard input, and if possible, please also include how to print text onto where my cursor is at.

I hope to use default python functions to achieve this, if impossible, see if possible to use python default modules to achieve this.

Thanks in advance!
for starters, look here: https://pypi.org/project/keyboard/
There are othre packages available, see: https://pypi.org/search/?q=keyboard
Please, is there something of a default module?
the link I show above is a default package, which can be used in your code using import.
If you don't like the 'keyboard' package, you can choose another.
You then use tha package directly in your code, no need to go to terminal (after install)

If you were to choose the 'keyboard' module, you would:
  1. Install keyboard package (from command line) with pip install keyboard This is a one time operation.
  2. import into your code, using import keyboard whenever code requires it (once at start of code)
  3. Use provided methods in your own code, see examples here: https://github.com/boppreh/keyboard
Default as in I don't need to install using pip. like OS is a built in module
OK, I get it.
Here's code that will capture Ctrl-c allowing you to clean up anything needed after Ctrl-c is pressed,
then exit the program gracefully
import time
import sys


def catch_ctrlc():
    try:
        while True:
            # program code goes here
            print("Running program commands")
            time.sleep(2)
    except KeyboardInterrupt:
        print("Captured keyboard Ctrl-c")
        print("I will exit the program now")
        sys.exit(0)
    finally:
        print("Do any cleanup here")


if __name__ == '__main__':
    catch_ctrlc()
running:
Output:
Running program commands Running program commands Running program commands Running program commands Running program commands ^CCaptured keyboard Ctrl-c I will exit the program now Do any cleanup here
If you want to catch other characters, you can do it with builtin curses,
see: https://docs.python.org/3/library/curses.html