如何在30秒后中断输入并退出程序? - 自动注销 - Python

时间:2017-07-20 09:30:39

标签: python python-3.x input

我想在30秒后自动注销。 程序等待用户输入内容,30秒后我希望程序自动关闭。 我有这样的事情:

import sys, time, os

def start_controller(user):

   start = time.time()
   PERIOD_OF_TIME = 30
   os.system('clear')
   print_menu()                            #printing menu
   choice = get_choice()                   #get input from view model
   while choice != "0":
       os.system('clear')
       if choice == "1":
           start += PERIOD_OF_TIME
           print_student_list(Student.student_list,AllAttendance.all_attendance_list)
       if time.time() > start + PERIOD_OF_TIME:
         os.system("clear")
         print('logout')
         Database.save_all_data_to_csv()
         sys.exit()

1 个答案:

答案 0 :(得分:2)

这是一个使用线程来获取和处理超时用户输入的简单示例。

我们创建一个Timer线程来执行超时功能,并等待守护程序线程中的用户输入。如果用户在指定的延迟周期内提供输入字符串,则取消定时器,否则定时器将设置finished事件以中断while循环。如果您需要进行任何最终清理,可以在while循环后执行此操作。

from threading import Thread, Timer, Event

def process_input(timer):
    s = input('> ')
    timer.cancel()
    print(s.upper())

delay = 30
finished = Event()
while not finished.isSet():
    timer = Timer(delay, finished.set)
    worker = Thread(target=process_input, args=(timer,))
    worker.setDaemon(True)
    worker.start()
    timer.start()
    timer.join()