python - Python主循环+子循环超时
问题描述
我想实现以下目标。
我有一个我正在工作的概念证明。我有单独的“命名 RFID”卡,然后我有“行动 RFID 卡”。所以我可能有这样的卡片:
Names
John - 12345
Mary - 12346
Actions
Start Work - 111
Finish Work - 222
Lunch - 333
所以约翰刷了他自己的卡片,然后刷了一张行动卡,记录了他的行动。
-Start Script
-Wait for User Card Input
-Once Input Received and Validated
- Wait for Action Card Input
- Start Timer
- Wait until Action Card Input matches a valid Action
- If a match, exit back to the main loop
- If no match, wait for one minute, then exit
-Continue Main Loop
我正在重用代码:
import time
timeout = time.time() + 60*5 # 5 minutes from now
while True:
test = 0
if test == 5 or time.time() > timeout:
break
test = test - 1
和一个 Python 游戏示例,它等待并永远循环玩游戏
https://dbader.org/blog/python-intro-reacting-to-user-input
我的测试代码如下(此时我没有进行卡片或动作查找,期望用户为 12345,卡片为 54321:(缩进四个空格的要求可能破坏了 Python 缩进)
#
# Guess My Number
#
import random
import time
# Set our game ending flag to False
game_running = True
while game_running:
# Greet the user to our game
print()
print("I'm thinking of a number between 1 and 10, can you guess it?")
# Have the program pick a random number between 1 and 10
#secret_number = random.randint(0, 10)
secret_number = 12345
card_number_list = 54321
# Set the player's guess number to something outside the range
guess_number = -1
# Loop until the player guesses our number
while guess_number != secret_number:
# Get the player's guess from the player
print()
guess = input("Please enter a number: ")
# Does the user want to quit playing?
if guess == "quit":
game_running = False
break
# Otherwise, nope, the player wants to keep going
else:
# Convert the players guess from a string to an integer
guess_number = int(guess)
# Did the player guess the program's number?
if guess_number == secret_number:
print()
print("Hi you have logged on, please swipe Card- if you don't Swipe - will timeout in 1 minute!")
timeout = time.time() + 60*1 # 1 minutes from now
while True:
test = 0
if test == 1 or time.time() > timeout:
card = input("Please enter your card number")
card_number = int(card)
if card_number == card_number_list:
print("Thanks for your card number")
test = 1
break
test = test - 1
# Otherwise, whoops, nope, go around again
else:
print()
print("You need to use your wrist band first...")
# Say goodbye to the player
print()
print("Thanks for playing!")
但是脚本没有退出,而是等待......
感谢任何反馈 - 我有基本的 Python 技能,并且正在尝试尽可能重用现有代码(感谢创建者!)。
解决方案
pythoninput()
函数在返回之前总是会等待键盘的响应。看看这个答案,了解一种实现你想要的技术。
推荐阅读
- php - $_GET['id'] 在传递带有 id 的 URL 时返回 null
- wordpress - 显示网站目录中的最后一张图片
- cobol - COBOL 数据类型转换
- c++ - C:结构中的 GMP 指针有问题
- javascript - 在 React 函数组件中传递特定的 props 以及 catch all props
- django - 如何在 django 模型序列化器中显示一个新字段?
- python - 如何使用列名作为变量?
- javascript - Rails 应用程序中的“ReferenceError:Chartkick 未定义” - 刷新后图表未显示
- function - 如何在电子表格中从 Yahoo Finance 导入历史数据 (CSV)
- python - 如何从 Seaborn 的计数图图形中删除标签名称?