[Python] How can I interrupt a while loop at any point immediately with a custom hot key?

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have some code that records controller input in a while loop. This is working fine except for the start/stop function. I want to be able to stop the loop at any point with a single key press.

    import inputs
    import msvcrt
    import keyboard

    def record():
    '''
    Start and stop the input recording with the "\" key
    Records controller inputs when they are pressed and depressed and at what time.
    '''
    print('To start recording, press "q". Press it again to stop')
    if msvcrt.getwch() == 'q':
    print ("recording started...")
    while True:
    events = inputs.get_gamepad()
    for event in events:
    print(event.code)
    record()


    This is one of the things I've tried doing. I've also tried putting the recording function in a thread using the threading module. However, the same issue arises. It's that when I press 'q' it waits until I press another button on my controller. I want it to immediately stop the loop.

    I've narrowed this down to the events = inputs.get_gamepad() line. It seems that it the loop waits here for a button to be pressed, then it can go back to the beginning causing the loop to correctly stop.

    import inputs
    import msvcrt
    import keyboard

    recording = True

    def interrupt_record():
    global recording
    recording = False

    def record():
    '''
    Start and stop the input recording with the "\" key
    Records controller inputs when they are pressed and depressed and at what time.
    '''
    print('To start recording, press "q". Press it again to stop')
    if msvcrt.getwch() == 'q':
    global recording
    recording = True
    print ("recording started...")

    while recording:
    events = inputs.get_gamepad()
    for event in events:
    print(event.code)

    keyboard.add_hotkey('q', interrupt_record)
    record()

    Continue reading...

Compartilhe esta Página