Search code examples
pythonwhile-loopkeypressrestart

Restart While Loop With Keypress


I am looking to restart a while loop with a keypress after it has been broke out of using the same key. Basically I am looking to make while loop that can be toggled on and of by a keypress. My code so far stops the loop with a keypress, but I have no idea how to start it again.

import keyboard
from time import sleep

key = "right shift"

while True:
    print("Running")
    sleep(0.5)
    if keyboard.is_pressed(key):
        break

I would describe the things I've tried here but I honestly have no idea.

Edit: Sorry for not being clear enough in the first place, but this is what I'm looking for:

If you wanted the loop to restart, then put another while loop around the current one, and put a line inside that one that waits for a keypress before it moves on to the inner loop.

I have done what Kyle recommended and it's working quite well, except for the fact that you have to hold the key to get it to stop. I believe it can be fixed with timings, here's what I have so far:

import keyboard
from time import sleep

key = "right shift"

while True:
    if keyboard.is_pressed(key):
        while True:
            print("Running")
            sleep(0.5)
            if keyboard.is_pressed(key):
                    sleep(1)
                    break

Solution

  • keyboard module has more features allowing different hooks/blockers.

    Just use keyboard.wait(key) to block the control flow until key is pressed:

    import keyboard
    from time import sleep
    
    key = "right shift"
    
    while True:
        print("Running")
        sleep(0.5)
        if keyboard.is_pressed(key):
            print('waiting for `shift` press ...')
            keyboard.wait(key)
    

    Sample interactive output:

    Running
    Running
    Running
    waiting for `shift` press ...
    Running
    Running
    Running
    Running
    Running
    waiting for `shift` press ...
    Running
    Running
    Running
    ...