Python多线程中断input() [英] Python multithreading interrupt input()

查看:605
本文介绍了Python多线程中断input()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是python的新手,我正在尝试创建一个程序来启动一个线程,该线程将在五秒钟后中断input()函数并显示消息"Done!".
目前,它仅打印完成!"输入后即使经过了五秒钟,用户也必须在消息完成!"之前输入内容.被陈列.我如何获得线程来中断input()函数?

Hi I am fairly new to python and I am trying to create a program that starts a thread that after five seconds will interrupt the input () function and print the message "Done!".
Currently it only prints "Done!" after input is given. Even after five seconds has passed, the user must enter input before the message "Done!" is displayed. How can I get the thread to interrupt the input() function?

import time
import threading

def fiveSec():
    time.sleep(5)
    print('Done!')

def main():
    t = threading.Thread(target = fiveSec)
    t.daemond = True
    t.start()
    input('::>')

if __name__ == '__main__':
    main()

(使用Python版本3.4.2)

(Using Python version 3.4.2)

推荐答案

您不需要线程即可执行此操作,而应使用信号:

You don't need a thread to do this, use a signal instead:

import signal
def interrupted(signum, frame):
    print "Timeout!"
signal.signal(signal.SIGALRM, interrupted)
signal.alarm(5)
try:
    s = input("::>")
except:
    print "You are interrupted."
signal.alarm(0)

您可以阅读有关信号模块的文档: https://docs.python.org/2/library/signal.html

You can read the documentation on signal module: https://docs.python.org/2/library/signal.html

这篇关于Python多线程中断input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆