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

2024-05-07 17:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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()

Tags: of程序gettimeossyssystemstart
1条回答
网友
1楼 · 发布于 2024-05-07 17:12:31

下面是一个简单的示例,它使用线程获取并处理带有超时的用户输入。在

我们创建一个计时器线程来执行超时功能,并在守护进程线程中等待用户输入。如果用户在指定的延迟时间内提供输入字符串,则计时器将被取消,否则计时器将设置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()

相关问题 更多 >