簡體   English   中英

如果未在規定時間內指定輸入,則終止 Python 程序

[英]Terminate Python program if input isn't specified in due timeframe

如果用戶在特定時間范圍內未提供輸入,例如 - 5 秒,我將嘗試終止 python 程序。

該代碼已從平庸的答案中提取和編輯

import sys
import time
from threading import Thread

x = None

def check():
    global x
    time.sleep(5)
    if x:
        print("Input has been given!")
        return
    sys.exit()

Thread(target=check).start()
x = input("Input something: ")

但是它一直在等待輸入並且不會終止,除非給出了輸入。 我怎樣才能更改代碼以使其按原樣執行?

你應該試試這個代碼它在 vscode 上的工作

import sys
import time
from threading import Thread

x = None

def check():
  global x
  time.sleep(5)
  if x:
    print("Input has been given!")
    return
  else:
    print("input has not been given for last 5 sec") 
    sys.exit()
if __name__=='__main__':
  t1=Thread(target=check)
  t1.start()

  x = input("Input something: ")
  t1.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM