Search code examples
pythonpython-3.xinputuser-input

How to do something till an input is detected in python3?


I want to execute a piece of code till the user enters an input(detects a random keypress), how do I do that in Python 3.x?

Here is the pseudo-code:

while input == False:
    print(x)

Solution

  • You can do it like this:

    try:
        while True:
            print("Running")
    except KeyboardInterrupt:
        print("User pressed CTRL+c. Program terminated.")
    

    The user just need to press Control+c.

    Python provide the built-in exception KeyboardInterrupt to handle this.

    To do it with any random key-press with pynput

    import threading
    from pynput.keyboard import Key, Listener
    
    class MyClass():
        def __init__(self) -> None:
            self.user_press = False
    
        def RandomPress(self, key):
            self.user_press = True
    
        def MainProgram(self):
            while self.user_press == False:
                print("Running")
            print("Key pressed, program stop.")
    
        def Run(self):
            t1 = threading.Thread(target=self.MainProgram)
            t1.start()
    
            # Collect events until released
            with Listener(on_press=self.RandomPress) as listener:
                listener.join()
    
    MyClass().Run()