python - 在命令行上运行 Python 程序时跳出循环
问题描述
我知道在使用 Windows 命令行时可以使用 Ctrl+C 退出正在运行的进程,但是当我尝试这样做以打破要求用户输入的 while 循环时,它不起作用。
这是我正在制作的一个小型 Black Jack 游戏的 run() 方法:
def run():
print('\t==================== Welcome to the Black Jack Casino ====================\n')
while True:
try:
player_chips = int(input('How many chips do you want to buy? '))
break
except:
print('Don\'t muck me about... ')
cash_out = False
dealer = Dealer()
player = Player()
player.chips = player_chips
while not cash_out or player.chips >= 0:
try:
player_bet = int(input('Place a bet: '))
if player_bet > player.chips:
print('You don\'t have the readies mate...')
else:
start_game(dealer, player, player_bet)
try:
quit = input('You want to continue? (Y/N) ')
if quit.lower() == 'n':
cash_out = True
except:
print('Don\'t talk rubbish...')
except:
print('Don\'t waste my time...')
continue
try:
play_again = input('Fancy another game? (Y/N)')
if play_again.lower() == 'y':
run()
else:
print('Next time then sucker...')
return
except:
print('Don\'t talk rubbish...')
当尝试 Ctrl+C 退出 while 循环时,它会提示我“下注”并打印“不要浪费我的时间......”。我怎样才能完成这项工作,因为一直退出cmd
然后重新导航到我的文件真的很烦人。谢谢
解决方案
我怎样才能完成这项工作,因为一直退出 cmd 然后重新导航到我的文件真的很烦人。谢谢
不要使用裸except
(except
没有指定异常类型的语句):在 Python 中,Ctrl-C 被转换为异常并引发。这意味着except
在没有更多信息的情况下将捕获它,并执行您定义的任何异常处理代码。
在 Python 中,您几乎总是希望显式捕获Exception
,因为它包含大多数异常,但重要的是排除KeyboardInterrupt
(这是 Ctrl-C 转换为的内容)和SystemExit
(这是sys.exit()
触发的内容)。请参阅异常层次结构。
对此的主要例外是执行清理然后直接重新引发,在这种情况下,可以接受裸露的例外(尽管通常是不必要的,因为如果进程被杀死,您通常不需要关闭文件等)。
顺便说一句,如果您需要定义自己的异常,这同样适用:它应该扩展Exception
,除非它是通常不应该被捕获和恢复的系统类型异常。
推荐阅读
- ios - 如何修复在 Delphi 中完成的示例应用程序 iOS 在启动后崩溃
- java - 如果我在复制的 ArrayList 中更改某些内容,则原始 ArrayList 值已更改。即使我使用了列表
empCopy=new ArrayList(原始列表) - html - 如何使用内联 css 将图像定位在 html 中?
- java - 即使在 pom.xml 中导入插件后也找不到 tomcat8-maven-plugin
- c++ - C++:在类主体之外定义但包含在标头保护中的成员函数的 ODR 冲突(如 YouCompleteMe 插件中所示)
- node.js - 我无法从前端将产品保存在数据库中,但它使用 Postman 来保存
- c++ - 删除字符串中最后一次出现的重复字符
- java - 字符串不是在 Android Studio 中的第一个按钮单击时构建的
- arrays - F# Creating a square sub-matrix from a square matrix
- javascript - on('click' 'li' function() 自动添加空格