1

I'm trying to write a script so that when I press "0" I will get an output, but I want to work without restarting the script, and I haven't been successful using the keyboard module which I've seen as being the most commonly used for detecting key inputs in Python.

What I have so far is

import keyboard

def goto(linenum):
    global line
    line = linenum
line = 1

if line == 1:
    while True:
        if keyboard.is_pressed('0'):
            print('pressed 0')
            break
        goto(1)

What I tried doing was after the loop breaks to refer back to the beginning of the loop and try again from there, however the script ends after I press 0. If I remove the break then it constantly outputs "pressed 0", which is not what I want to happen.

2 Answers 2

2

You can use pynput to detect key input.

I would do something like this:

from pynput.keyboard import Key, Listener

def on_press(key):
    if str(key).replace("'","") == '0':
        print('pressed 0')

listener = Listener(on_press=on_press)
listener.start()

Once you start the listener, it will be always waiting for the key press and you can still add code after. In fact, with this example I recommend to add something after, maybe an input() so the script won't close immediately.

Sign up to request clarification or add additional context in comments.

1 Comment

Alright so I gave this a go and it just ends the script instantly with no error or feedback of any kind. Then when I added input() like you suggested, I was getting the kind of feedback I was looking for, thank you.
0

I think there are a few problems going on here.

  1. goto is a pretty bad pattern to use and I don't think there's anything here to make your implementation work. It kinda sounds like you're going for some kind of recursion like approach here where when 0 is pressed, then it does some 'reset' and starts looping again. If that is the case you could do something like this:
def wait_for_zero():
    # wait for press here
    # Should add some sort of exit check too
    # 'reset' logic, if any here
    wait_for_zero()
  1. looping with a weak condition is pretty fast cycling and generally a bad idea without some time delay. This is mentioned in the documentation for keybaord. There also is an example in the documentation for keyboard to wait for a keypress: https://github.com/boppreh/keyboard#waiting-for-a-key-press-one-time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.