python - 如果没有响应,给用户提示
问题描述
我正在尝试创建一个程序,该程序通过对问题的三个回答来要求用户输入。现在我的问题几乎是一段长的,但理想情况下,我想先问一个初始问题,然后如果用户在任何时间内没有输入任何内容,就开始给出提示。
answers = []
def questions(question):
print(question)
for i in range(1, 4, 1):
answers.append(input(f"{i}. "))
questions("""What are your three favorite things? """)
理想情况下,会有一些行为类似于下面的伪代码:
ask user for input
if no response within 30 seconds:
give first hint
elif no respose within 30 seconds:
give second hint
提前致谢!
解决方案
您可以创建一个hint
等待一段时间然后输出提示的过程。如果用户回答了问题,则使用terminate()hint
终止进程。
import time
from multiprocessing import Process
answers = []
def questions(question):
print(question)
for i in range(1, 4, 1):
answers.append(answer(f"{i}. "))
print(answers)
def hint():
# For testing simplification, I decrease the wait time
time.sleep(5)
print('\nhint1 after 5 seconds')
time.sleep(3)
print('hint2 after 3 seconds')
def answer(i):
phint = Process(target=hint)
phint.start()
uanswer = input(i)
phint.terminate()
return uanswer
questions("""What are your three favorite things? """)
输出看起来像
What are your three favorite things?
1.
hint1 after 5 seconds
hint2 after 3 seconds
test
2.
hint1 after 5 seconds
test1
3. test3
['test', 'test1', 'test3']
推荐阅读
- javascript - 在 stat 方法之前检查权限以避免错误
- perl - perl STDIN 到子程序
- coinbase-api - HTTP 400 错误:大小太准确。最小单位是 0.00000001
- reactjs - 如何使用 jest 和酶测试具有异步功能的 React 组件
- python - python日志控制台和文件输出包含重复的消息
- javascript - JS中通过onclick访问对象外的方法
- laravel - 将会话从 memcached 迁移到 redis 而无需在 laravel 中注销用户
- angular - (我的地址 url api)的 Http 失败响应:0 未知错误
- flutter - 如何改变未来
在 dart:flutter 中串起来 - php - 将旧 php 和 mysql 版本的网站上传到具有新 php 和 mysql 版本的服务器