英文:
How do I make it so when I press the escape key that it exits the loop?
问题
I am trying to make it so that when I press escape, it will exit the loop at any time. I was hoping that it would work with importing the keyboard module, but I think the issue is because it was opening in a command prompt window instead of working in the IDE.
import subprocess
import sys
import time
import random
import msvcrt
def print_with_typing(text):
for char in text:
print(char, end='', flush=True)
time.sleep(0.01) # 调整延迟(以秒为单位)以控制打字速度
def start_new_window():
subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
sys.exit()
if len(sys.argv) > 1 and sys.argv[1] == "new_window":
print("running in a new window\n\n")
else:
print("Opening a new window...")
start_new_window()
running = True
while running:
daily_income = 0
wallet_amount = random.randint(5, 100)
print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
print_with_typing("Hello, \nWelcome to That Food Place!\n")
time.sleep(1)
name = input("What is your name?\n")
print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
time.sleep(1)
entree = [
("Dino Nuggets", "5 minutes", 5),
("Veggie Fries", "10 minutes!", 6),
("Impossible Steak", "20 minutes!", 25),
("Cheese Log", "15 minutes!", 10),
("Lobster Wings", "25 minutes!", 50),
]
sides = [
("French onion sticks", 2),
("Frog legs", 4),
("Buttered toast", 1),
("Crunch rat", 2),
("Apple", 1),
("Roasted stank", 10),
]
drinks = [
("Water", ""),
("Four loko", ""),
("Liquid grass", ""),
("Dirty water", ""),
("Coka", ""),
]
print_with_typing("\nOur menu today consists of the following options:\n")
for item in entree:
print_with_typing("- " + item[0] + "\n")
time.sleep(2)
order_list = [] # 存储客户的订单
while running:
order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
if order.lower() == "done":
break
found_entree = None
found_side = None
found_drink = None
for item in entree:
if item[0].lower() in order.lower():
found_entree = item
break
for item in sides:
if item[0].lower() in order.lower():
found_side = item
break
for item in drinks:
if item[0].lower() in order.lower():
found_drink = item
break
if found_entree:
item_price = found_entree[2]
if item_price <= wallet_amount:
side_order = input("Would you like a side and a drink with that?\n")
if side_order.lower() == "yes":
# 提示选择配菜
print_with_typing("Please choose a side from the following options:\n")
for side in sides:
print_with_typing("- " + side[0] + "\n")
selected_side = input()
found_side = None
for side in sides:
if side[0].lower() == selected_side.lower():
found_side = side
break
if found_side:
order_list.append(found_side[0])
print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")
drink_order = input("Would you like a drink as well?\n")
if drink_order.lower() == "yes":
# 提示选择饮料
print_with_typing("Please choose a drink from the following options:")
for drink in drinks:
print_with_typing("- " + drink[0] + "\n")
selected_drink = input()
found_drink = None
for drink in drinks:
if drink[0].lower() == selected_drink.lower():
found_drink = drink
break
if found_drink:
order_list.append(found_drink[0])
print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
else:
print_with_typing("Alrighty then!\n")
print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
wallet_amount -= item_price
daily_income += item_price
order_list.append(found_entree[0]) # 将点的菜品添加到订单列表中
time.sleep(1)
print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
time.sleep(1)
print_with_typing("$" + str(wallet_amount) + " remaining\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from the listed options!\n")
continue
order_more = input("Would you like to order something else?\n")
if order_more.lower() == "no":
break
time.sleep(3)
print_with_typing("\nHere are your orders. Enjoy!\n")
for item in order_list:
print_with_typing("- " + item + "\n")
time.sleep(1)
opinion = input("Did you enjoy your meal, " + name + "?\n")
if "no" in opinion.lower():
print_with_typing("I am sorry to hear that. Please enjoy a refund on your order!\n")
wallet_amount += item_price
print("Refunded " + str(item_price))
print("Current wallet amount = $" + str(wallet_amount))
elif "yes" in opinion.lower():
print_with_typing("I am happy to hear that! Enjoy the rest of your day!\n")
time.sleep(2)
print_with_typing("Next customer, please!\n\n\n")
if m
<details>
<summary>英文:</summary>
I am trying to make it so that when I press escape, it will exit the loop at anytime. I was hoping that it would work with importing keyboard but I think the issue is because it was opening in a command prompt window instead of working in the IDE.
import subprocess
import sys
import time
import random
import msvcrt
def print_with_typing(text):
for char in text:
print(char, end='', flush=True)
time.sleep(0.01) # Adjust the delay (in seconds) to control the typing speed
def start_new_window():
subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
sys.exit()
if len(sys.argv) > 1 and sys.argv[1] == "new_window":
print("running in new window\n\n")
else:
print("Opening a new window...")
start_new_window()
running = True
while running:
daily_income = 0
wallet_amount = random.randint(5, 100)
print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
print_with_typing("Hello, \nWelcome to That Food Place!\n")
time.sleep(1)
name = input("What is your name?\n")
print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
time.sleep(1)
entree = [
("Dino Nuggets", "5 minutes", 5),
("Veggie Fries", "10 minutes!", 6),
("Impossible Steak", "20 minutes!", 25),
("Cheese Log", "15 minutes!", 10),
("Lobster Wings", "25 minutes!", 50),
]
sides = [
("French onion sticks", 2),
("Frog legs", 4),
("Buttered toast", 1),
("Crunch rat", 2),
("Apple", 1),
("Roasted stank", 10),
]
drinks = [
("Water", ""),
("Four loko", ""),
("Liquid grass", ""),
("Dirty water", ""),
("Coka", ""),
]
print_with_typing("\nOur menu today consists of the following options:\n")
for item in entree:
print_with_typing("- " + item[0] + "\n")
time.sleep(2)
order_list = [] # Store the customer's orders
while running:
order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
if order.lower() == "done":
break
found_entree = None
found_side = None
found_drink = None
for item in entree:
if item[0].lower() in order.lower():
found_entree = item
break
for item in sides:
if item[0].lower() in order.lower():
found_side = item
break
for item in drinks:
if item[0].lower() in order.lower():
found_drink = item
break
if found_entree:
item_price = found_entree[2]
if item_price <= wallet_amount:
side_order = input("Would you like a side and drink with that?\n")
if side_order.lower() == "yes":
# Prompt for side selection
print_with_typing("Please choose a side from the following options:\n")
for side in sides:
print_with_typing("- " + side[0] + "\n")
selected_side = input()
found_side = None
for side in sides:
if side[0].lower() == selected_side.lower():
found_side = side
break
if found_side:
order_list.append(found_side[0])
print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")
drink_order = input("Would you like a drink as well?\n")
if drink_order.lower() == "yes":
# Prompt for drink selection
print_with_typing("Please choose a drink from the following options:")
for drink in drinks:
print_with_typing("- " + drink[0] +"\n")
selected_drink = input()
found_drink = None
for drink in drinks:
if drink[0].lower() == selected_drink.lower():
found_drink = drink
break
if found_drink:
order_list.append(found_drink[0])
print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
else:
print_with_typing("Alrighty then!\n")
print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
wallet_amount -= item_price
daily_income += item_price
order_list.append(found_entree[0]) # Add the ordered item to the order list
time.sleep(1)
print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
time.sleep(1)
print_with_typing("$" + str(wallet_amount) + " remaining\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from an item listed!\n")
continue
order_more = input("Would you like to order something else?\n")
if order_more.lower() == "no":
break
time.sleep(3)
print_with_typing("\nHere are your orders. Enjoy!\n")
for item in order_list:
print_with_typing("- " + item + "\n")
time.sleep(1)
opinion = input("Did you enjoy your meal, " + name + "?\n")
if "no" in opinion.lower():
print_with_typing("I am sorry to hear that. Please enjoy a refund on your order!\n")
wallet_amount += item_price
print("Refunded " + str(item_price))
print("Current wallet amount = $" + str(wallet_amount))
elif "yes" in opinion.lower():
print_with_typing("I am happy to hear that! Enjoy the rest of your day!\n")
time.sleep(2)
print_with_typing("Next customer, please!\n\n\n")
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b': # Check if Escape key is pressed
running = False
print_with_typing("Thank you for visiting That Food Place. Have a great day!\n")
print_with_typing("Daily income = $" + str(daily_income))
time.sleep(5)
sys.exit()
I tried importing msvcrt after some research and I was able to get it to work once while mashing the escape key the entire time it was running but I haven't been able to exit consistently.
This is my first pet project so any help. I'm adding more from time to time to get more familiar with different concepts in python so all tips and tricks are appreciated!
</details>
# 答案1
**得分**: 1
你编写的这个程序方式不允许你通过按下Escape键来中断,因为它没有事件循环。
执行是逐行按文件的顺序进行的,所以只能在循环的最末尾检查是否按下了Escape键。
如果你只想停止程序而不必经历整个过程,请按CTRL+C。这是一个特殊的键,会向你的程序发送一个信号,从而引发异常。信号是一种由操作系统处理的特殊交互方式。
如果你真的想使用Escape键来退出,你需要改变程序的结构。在Windows中,最好的解决方案是使用GUI框架(在Windows中终端UI并不是很发达)。对于Python初学者来说,tkinter是一个不错的首选。
<details>
<summary>英文:</summary>
The way you wrote this program does not let you interrupt with escape because it does not have an event loop.
The execution is line by line in the order of the file, so it will only be able to check for escape keypress at the very end of the loop.
If you just want to stop the program without going through the entire process, press CTRL+C. This is a special key that send a signal to your program that will raise an exception in response. Signals are a special kind of interaction that is handled by the OS.
If you really want to use escape to quit, you need to change the structure of your program. In windows, the best solution is to use a GUI framework (terminal UI are not very developed in windows). For a beginner in Python tkinter is a good first choice.
</details>
# 答案2
**得分**: 0
我建议您使用`signal`库,只需监听`Ctrl`和`X`键的按键事件。
```python
# 基本导入
import subprocess
import sys
import time
import random
import msvcrt
import signal # 导入信号处理程序库
running = True # 在顶层定义
# 定义Ctrl和X键被按下时要执行的操作
def signal_handler(signal, frame):
print("Ctrl + X detected. Exiting...")
# 放置您的关闭代码在这里。
running = False # 更改为false
exit(0)
# 在这里注册您的处理程序
signal.signal(signal.SIGINT, signal_handler)
# 主要代码逻辑在这里
def print_with_typing(text):
for char in text:
print(char, end='', flush=True)
time.sleep(0.01) # 调整延迟(以秒为单位)以控制打字速度
def start_new_window():
subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
sys.exit()
if len(sys.argv) > 1 and sys.argv[1] == "new_window":
print("running in new window\n\n")
else:
print("Opening a new window...")
start_new_window()
while running:
daily_income = 0
wallet_amount = random.randint(5, 100)
print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
print_with_typing("Hello, \nWelcome to That Food Place!\n")
time.sleep(1)
name = input("What is your name?\n")
print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
time.sleep(1)
entree = [
("Dino Nuggets", "5 minutes", 5),
("Veggie Fries", "10 minutes!", 6),
("Impossible Steak", "20 minutes!", 25),
("Cheese Log", "15 minutes!", 10),
("Lobster Wings", "25 minutes!", 50),
]
sides = [
("French onion sticks", 2),
("Frog legs", 4),
("Buttered toast", 1),
("Crunch rat", 2),
("Apple", 1),
("Roasted stank", 10),
]
drinks = [
("Water", ""),
("Four loko", ""),
("Liquid grass", ""),
("Dirty water", ""),
("Coka", ""),
]
print_with_typing("\nOur menu today consists of the following options:\n")
for item in entree:
print_with_typing("- " + item[0] + "\n")
time.sleep(2)
order_list = [] # 存储顾客的订单
while running:
order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
if order.lower() == "done":
break
found_entree = None
found_side = None
found_drink = None
for item in entree:
if item[0].lower() in order.lower():
found_entree = item
break
for item in sides:
if item[0].lower() in order.lower():
found_side = item
break
for item in drinks:
if item[0].lower() in order.lower():
found_drink = item
break
if found_entree:
item_price = found_entree[2]
if item_price <= wallet_amount:
side_order = input("Would you like a side and drink with that?\n")
if side_order.lower() == "yes":
# 提示选择配菜
print_with_typing("Please choose a side from the following options:\n")
for side in sides:
print_with_typing("- " + side[0] + "\n")
selected_side = input()
found_side = None
for side in sides:
if side[0].lower() == selected_side.lower():
found_side = side
break
if found_side:
order_list.append(found_side[0])
print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")
drink_order = input("Would you like a drink as well?\n")
if drink_order.lower() == "yes":
# 提示选择饮料
print_with_typing("Please choose a drink from the following options:")
for drink in drinks:
print_with_typing("- " + drink[0] + "\n")
selected_drink = input()
found_drink = None
for drink in drinks:
if drink[0].lower() == selected_drink.lower():
found_drink = drink
break
if found_drink:
order_list.append(found_drink[0])
print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
else:
print_with_typing("Alrighty then!\n")
print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
wallet_amount -= item_price
daily_income += item_price
order_list.append(found_entree[0]) # 将订购的项目添加到订单列表
time.sleep(1)
print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
time.sleep(1)
print_with_typing("$" + str(wallet_amount) + " remaining\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from an item listed!\n")
continue
order_more = input("Would you like to order something else?\n")
if order_more.lower() == "no":
break
time.sleep(3)
print_with_typing("\nHere are your orders. Enjoy!\n")
for item in order_list:
print_with_typing("- " + item + "\n")
time.sleep(1)
opinion = input("Did you enjoy your meal, " + name + "?\n")
if "no" in opinion.lower():
print_with_typing("I am sorry to hear that. Please enjoy a refund on your
<details>
<summary>英文:</summary>
I suggest you use the `signal` library and just listen for a `Ctrl` and `X` key press
```python
# Base imports
import subprocess
import sys
import time
import random
import msvcrt
import signal # Import signal handler llibrary
running = True # define at top level
# define what to do when ctrl and x are pressed
def signal_handler(signal, frame):
print("Ctrl + X detected. Exiting...")
#put your closing code here.
running = False # change to false
exit(0)
# Register your handler here
signal.signal(signal.SIGINT, signal_handler)
# Main code logic here
def print_with_typing(text):
for char in text:
print(char, end='', flush=True)
time.sleep(0.01) # Adjust the delay (in seconds) to control the typing speed
def start_new_window():
subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
sys.exit()
if len(sys.argv) > 1 and sys.argv[1] == "new_window":
print("running in new window\n\n")
else:
print("Opening a new window...")
start_new_window()
while running:
daily_income = 0
wallet_amount = random.randint(5, 100)
print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
print_with_typing("Hello, \nWelcome to That Food Place!\n")
time.sleep(1)
name = input("What is your name?\n")
print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
time.sleep(1)
entree = [
("Dino Nuggets", "5 minutes", 5),
("Veggie Fries", "10 minutes!", 6),
("Impossible Steak", "20 minutes!", 25),
("Cheese Log", "15 minutes!", 10),
("Lobster Wings", "25 minutes!", 50),
]
sides = [
("French onion sticks", 2),
("Frog legs", 4),
("Buttered toast", 1),
("Crunch rat", 2),
("Apple", 1),
("Roasted stank", 10),
]
drinks = [
("Water", ""),
("Four loko", ""),
("Liquid grass", ""),
("Dirty water", ""),
("Coka", ""),
]
print_with_typing("\nOur menu today consists of the following options:\n")
for item in entree:
print_with_typing("- " + item[0] + "\n")
time.sleep(2)
order_list = [] # Store the customer's orders
while running:
order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
if order.lower() == "done":
break
found_entree = None
found_side = None
found_drink = None
for item in entree:
if item[0].lower() in order.lower():
found_entree = item
break
for item in sides:
if item[0].lower() in order.lower():
found_side = item
break
for item in drinks:
if item[0].lower() in order.lower():
found_drink = item
break
if found_entree:
item_price = found_entree[2]
if item_price <= wallet_amount:
side_order = input("Would you like a side and drink with that?\n")
if side_order.lower() == "yes":
# Prompt for side selection
print_with_typing("Please choose a side from the following options:\n")
for side in sides:
print_with_typing("- " + side[0] + "\n")
selected_side = input()
found_side = None
for side in sides:
if side[0].lower() == selected_side.lower():
found_side = side
break
if found_side:
order_list.append(found_side[0])
print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")
drink_order = input("Would you like a drink as well?\n")
if drink_order.lower() == "yes":
# Prompt for drink selection
print_with_typing("Please choose a drink from the following options:")
for drink in drinks:
print_with_typing("- " + drink[0] +"\n")
selected_drink = input()
found_drink = None
for drink in drinks:
if drink[0].lower() == selected_drink.lower():
found_drink = drink
break
if found_drink:
order_list.append(found_drink[0])
print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
else:
print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
else:
print_with_typing("Alrighty then!\n")
print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
wallet_amount -= item_price
daily_income += item_price
order_list.append(found_entree[0]) # Add the ordered item to the order list
time.sleep(1)
print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
time.sleep(1)
print_with_typing("$" + str(wallet_amount) + " remaining\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
else:
time.sleep(1)
print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from an item listed!\n")
continue
order_more = input("Would you like to order something else?\n")
if order_more.lower() == "no":
break
time.sleep(3)
print_with_typing("\nHere are your orders. Enjoy!\n")
for item in order_list:
print_with_typing("- " + item + "\n")
time.sleep(1)
opinion = input("Did you enjoy your meal, " + name + "?\n")
if "no" in opinion.lower():
print_with_typing("I am sorry to hear that. Please enjoy a refund on your order!\n")
wallet_amount += item_price
print("Refunded " + str(item_price))
print("Current wallet amount = $" + str(wallet_amount))
elif "yes" in opinion.lower():
print_with_typing("I am happy to hear that! Enjoy the rest of your day!\n")
time.sleep(2)
print_with_typing("Next customer, please!\n\n\n")
print_with_typing("Thank you for visiting That Food Place. Have a great day!\n")
print_with_typing("Daily income = $" + str(daily_income))
time.sleep(5)
sys.exit()
The script will keep running until the user presses "Ctrl + X" or "Ctrl + C", at which point the signal_handler function will be executed, allowing you to handle the interruption gracefully.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论