Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python程序中提供超时_Python_Interrupt - Fatal编程技术网

在Python程序中提供超时

在Python程序中提供超时,python,interrupt,Python,Interrupt,我正在用python编写一个程序,它接受两个输入 一旦用户给出第一个输入,他就有10秒的时间来给出第二个输入。 如果用户能够在这10秒内提供第二个值并按下enter键,计时器将停止并转到程序的下一部分 python中是否有任何功能允许我在10秒后提供中断并停止接受第二个输入。如果给出了第二个输入,则停止计时器。您可以创建一个自定义计时器类,并在不同的线程中启动它。一旦超时发生(10秒后),您可以将SIGINT信号发送回父线程,这将引发KeyboardInterrupt异常,我们在main()函数

我正在用python编写一个程序,它接受两个输入

一旦用户给出第一个输入,他就有10秒的时间来给出第二个输入。 如果用户能够在这10秒内提供第二个值并按下enter键,计时器将停止并转到程序的下一部分

python中是否有任何功能允许我在10秒后提供中断并停止接受第二个输入。如果给出了第二个输入,则停止计时器。

您可以创建一个自定义计时器类,并在不同的线程中启动它。一旦超时发生(10秒后),您可以将
SIGINT
信号发送回父线程,这将引发
KeyboardInterrupt
异常,我们在
main()
函数中捕获该异常。否则,您可以在用户在正确的时间输入第二个输入后停止计时器,这将停止计时器线程。此外,我们可以检查
键盘中断是否是由于超时或用户操作而发生的

注意:当我们向主进程发送信号时,我们还需要检查运行程序的平台。看

演示:

解决方案:

import time
import threading
import os
import signal


class Timer(threading.Thread):
    _timeout = False
    _timer = 0
    _stopped = False

    def __init__(self, delay):
        super(Timer, self).__init__()
        self.restart(delay)

    def is_timeout(self):
        return self._timeout

    def stop(self):
        self._stopped = True

    def restart(self, delay):
        self._stopped = False
        self._timer = time.time() + delay

    def run(self):

        while not self._stopped:
            time.sleep(0.1)
            if time.time() >= self._timer:
                break
        if not self._stopped:
            self._timeout = True

            # check os name
            if os.name == 'nt':
                # we are on Windows
                os.kill(os.getpid(), signal.CTRL_C_EVENT)
            else:
                # we are on a Posix/Unix (or very unlikely on java) system
                os.kill(os.getpid(), signal.SIGINT)


def main():
    first_input = input('First input:')

    delay = 10
    timer = Timer(delay)
    timer.daemon = True

    try:
        print('\nStarting the timer for the second input %r second(s)' % delay)
        timer.start()

        second_input = input('Second input:')

        print('\nWell done. Stopping the timer!\n')
        timer.stop()

        print('Input values: %r %r\n' % (first_input, second_input))

        # do your stuff here...

    except KeyboardInterrupt:
        if timer.is_timeout():
            print("\nTimeout!")
        else:
            print("\nUser interrupted the input")


main()

为此,您需要使用多线程解决方案,因为这是一个相对简单的要求,所以您可能可以使用。python idle标记是关于idle编辑器和shell的,而不是“什么都不做”。无论如何,您可以使用一个简单的tkinter程序,使用一个条目和一个.after回调,轻松地完成您想要的任务。