mime
mime

Reputation: 312

How do I detect Ctrl+Key in Python without having to download other modules?

I am writing a command-line notepad program and I want to detect keyboard press combinations, for example, Ctrl+S and Ctrl+D. I have found many codes which work, but they all require me to download a module, like the keyboard module. However, my parents have set restrictions such that I am not able to download any modules. Could someone give me an alternative to the following code:

import keyboard as kb
while True:
    if kb.is_pressed("ctrl+s"):
        print("Ctrl+s is pressed!")

without having to download external modules?

Upvotes: 2

Views: 1787

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 99011

Since you're on windows, you can use the built-in msvcrt module, i.e.:

import msvcrt
from time import sleep

while 1:
    if msvcrt.kbhit():
        key = msvcrt.getch()
        # print(key) # uncomment to see which keys are being pressed.
        if key == b"\x13":
            print("CTRL+S")

    sleep(0.05) # Added to reduce cpu load, 5% before, 0.01% after

Notes:

Run it on a console, not inside the IDE.

  • python3 myscript.py

Upvotes: 1

Related Questions