Python:使用计时器终止循环

时间:2018-10-16 16:24:11

标签: 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()

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

选中此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)