Home > Net >  How to interrupt a loop in python with the input of a key but without stopping the cycle to verify i
How to interrupt a loop in python with the input of a key but without stopping the cycle to verify i

Time:12-18


while(True):

   print("Enter to the bucle")
   with open('the_file.txt', 'w') as f:
       f.write('Hello world!\n')
   f.close()

   #if at some point during the execution of this loop press the letter, for example the key q, that a break is set and the while () loop closes

The problem i found is that if i use an input () and save the key as a string, that would be stopping the loop at the keyboard input wait point, but what i was looking for is that it doesn't have a point where it stops for wait for the keyboard input but simply if at some point the q was pressed, the cycle would end and it would not be executed again

CodePudding user response:

Sample code using threading. We run task in the background and parse user input for key/enter in another thread.

is_interrupt_task = True will interrupt the task otherwise it will not even if main thread has already exited.

Code

import logging
import threading
import time

format = '%(asctime)s: %(message)s'
logging.basicConfig(format=format, level=logging.INFO, datefmt='%H:%M:%S')


def task(name):
    logging.info(f'Thread {name}: starting')
    for i in range(10):
        time.sleep(i)
        logging.info(f'Thread {name}: sleeps for {i}s')

    logging.info(f'Thread {name}: task is completed.')


if __name__ == "__main__":
    # Run task in the background.
    is_interrupt_task = True
    mytask = threading.Thread(target=task, args=(1,), daemon=is_interrupt_task)
    mytask.start()

    logging.info('starting main loop ...')
    while True:  
        userinput = input()
        command = userinput.strip()

        if command:  # almost all keys
            logging.info("main quits")
            break

        # if command == 'q':
            # logging.info("main quits")
            # break

Example task is interrupted

16:12:29: Thread 1: starting
16:12:29: starting main loop ...
16:12:29: Thread 1: sleeps for 0s
16:12:30: Thread 1: sleeps for 1s
16:12:32: Thread 1: sleeps for 2s
16:12:35: Thread 1: sleeps for 3s
q
16:12:36: main quits

Example task is allowed to finish

is_interrupt_task = False

16:11:12: Thread 1: starting
16:11:12: starting main loop ... 
16:11:12: Thread 1: sleeps for 0s
16:11:13: Thread 1: sleeps for 1s
16:11:15: Thread 1: sleeps for 2s
16:11:18: Thread 1: sleeps for 3s
q
16:11:22: main quits
16:11:22: Thread 1: sleeps for 4s
16:11:27: Thread 1: sleeps for 5s
16:11:33: Thread 1: sleeps for 6s
16:11:40: Thread 1: sleeps for 7s
16:11:48: Thread 1: sleeps for 8s
16:11:57: Thread 1: sleeps for 9s
16:11:57: Thread 1: task is completed.
  • Related