如何通过输入一个键来中断python中的循环,但不停止循环以验证每次执行时是否输入?

How to interrupt a loop in python with the input of a key but without stopping the cycle to verify if it is entered every time it is executed?


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

我发现的问题是,如果我使用输入 () 并将键保存为字符串,那将在键盘输入等待点停止循环,但我正在寻找的是它不会'它没有停止等待键盘输入的点,但只要在某个时候按下 q,循环就会结束并且不会再次执行

使用线程的示例代码。我们 运行 在后台执行任务并在另一个线程中解析 key/enter 的用户输入。

is_interrupt_task = True会中断任务,否则即使主线程已经退出也不会。

代码

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

示例任务被中断

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

允许示例任务完成

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.