macos - 中断 python 输入的问题 (Mac)
问题描述
我试图允许用户输入多个答案,但只能在分配的时间内。问题是我让它运行但程序不会中断输入。如果用户在时间结束后输入答案,程序只会停止用户输入。有任何想法吗?我想在 python 中做的甚至可能吗?
我尝试过使用线程和信号模块,但是它们都会导致相同的问题。
使用信号:
import signal
def handler(signum, frame):
raise Exception
def answer_loop():
score = 0
while True:
answer = input("Please input your answer")
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
try:
answer_loop()
except Exception:
print("end")
signal.alarm(0)
使用线程:
from threading import Timer
def end():
print("Time is up")
def answer_loop():
score = 0
while True:
answer = input("Please input your answer")
time_limit = 5
t = Timer(time_limit, end)
t.start()
answer_loop()
t.cancel()
解决方案
您的问题是内置input
没有超时参数,并且,AFAIK,线程不能被其他线程终止。我建议您使用带有事件的 GUI 来精细控制用户交互。这是一个简单的 tkinter 示例。
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='answer')
entry = tk.Entry(root)
label.pack()
entry.pack()
def timesup():
ans = entry.get()
entry.destroy()
label['text'] = f"Time is up. You answered {ans}"
root.after(5000, timesup)
root.mainloop()
推荐阅读
- laravel - Laravel 重置密码错误?
- mysql - 创建表不存在错误“操作数应包含 1 个列”
- c# - 如何使用 C# 以编程方式在 OpenFile 对话框中选择文件
- ios - 带有 URLSession 的 Swift iOS -DispatchGroup 正在锁定它不位于的应用程序的其他部分
- batch-file - 嵌套 for 循环中 EnableDelayedExpansion 的语法
- php - 检查多维数组的重复项(第 3 级)
- google-analytics - 谷歌分析 (gtag) 跨域
- python - 返回函数给出无
- c# - 获取我的时区的当前日期
- swift - SKTileMapNode 未加载到正确的大小