Python:使用定时器终止循环

标签 python python-3.x multithreading loops

我是 python 的新手,并且正在按照这种逻辑从事学校项目:用户必须在给定时间内尽快回答一系列问题。

例如,分配的时间是 30 秒,我会循环浏览问题字典并获得答案。超时时,循环将开始,即使脚本仍在等待输入。

def start_test():
    for item on questions:
        print(item)
        answers.append(input(' : '))

我试过使用多处理和多线程,但我发现 stdin 不能处理子进程。

我正在寻找类似的东西:

while duration > 0:
    start_test()

def countdown():
    global duration
    while duration > 0:
        duration -= 1
        time.sleep(1)
    # something lime start_test().stop()

但我不知道如何与 start_test 函数并行运行 countdown 函数。

有什么想法吗?

最佳答案

据我所知,输入只能通过主线程访问。我可能错了。 但是,如果是这种情况,您需要非阻塞输入。

检查这个blog .以下答案基于此。

注意:这是一个非常快速且肮脏的解决方案。

我已经在 Linux 上检查过了。 如果它在 Windows 上不起作用,请尝试 this 链接以供进一步引用。

import _thread
import sys
import select
import time

def start_test():
        questions = ['1','2','3']
        answers = []

        for item in questions:
            print(item)

            # Input in a non-blocking way
            loop_flag = True
            while loop_flag:
                # Read documenation and examples on select
                ready =  select.select([sys.stdin], [], [], 0)[0]

                if not ready:
                    # Check if timer has expired
                    if timeout:
                        return answers
                else:
                    for file in ready:
                        line = file.readline()
                        if not line: # EOF, input is closed
                            loop_flag = False
                            break 
                        elif line.rstrip():
                            # We have some input
                            answers.append(line)
                            # So as to get out of while
                            loop_flag = False 
                            # Breaking out of for
                            break
        
        return answers
        
def countdown():
        global timeout
        time.sleep(30)
        timeout = True
    
# Global Timeout Flag
timeout = False

timer = _thread.start_new_thread(countdown, ())

answers = start_test()
print(answers)

关于Python:使用定时器终止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839976/

相关文章:

java - 访问被其他线程修改的Set

python - 将 emacs 组织模式表读入 python pandas 数据帧的优雅方式

python - super 应该始终位于 __init__ 方法的顶部,还是可以位于底部?

python - 从远程数据库获取并存储到本地 Django

python - 查找字符串中特定字符的范围

c# - 以编程方式限制在服务中运行的线程的 CPU 使用率

python - 将值拆入 Pandas DataFrame 中的不同行

python - 实现双向链表的问题

python - 如果 panda 中的值为 Nan,则合并两行

c# - 在多线程应用程序中使用 Thread.Sleep 的原因是什么?