简体   繁体   English

用Python中的用户输入结束循环

[英]End loop with user input in Python

I have a this update function: 我有一个更新功能:

def update(self, interval=60):
    while True:
        # Do stuff

        time.sleep(interval)

I would like to know the possible ways to, once the function is called, interrupt the loop via user input while leaving the script running. 我想知道调用该函数后,可以通过用户输入中断循环,同时保持脚本运行的可能方法。

All I found were answer from 5+ years ago, mostly platform-dependant.Is there any new/reliable way to achieve this? 我发现的答案都是5年前以上的答案,主要取决于平台。是否有任何新的/可靠的方法来实现这一目标? I would rather avoid threading, if possible. 如果可能的话,我宁愿避免线程化。 Using 3.7 使用3.7

You could create an interrupt handler with signal . 您可以使用signal创建一个中断处理程序。 This, however, still relies on the system thread for monitoring; 但是,这仍然依赖于系统线程进行监视。 I don't think it's costly since the thread is already spawned. 我不认为这是昂贵的,因为线程已经产生。

In essence, you'd still need a sort of global flag that governs the loop. 从本质上讲,您仍然需要一种控制循环的全局标志。 When the interrupt trigger happens (user input, etc.), the interrupt changes the value of the flag, and the loop terminates allowing for other processing. 当发生中断触发(用户输入等)时,中断将更改标志的值,并且循环终止以进行其他处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM