首页 > 解决方案 > 在命令行上运行 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然后重新导航到我的文件真的很烦人。谢谢

标签: pythoncommand-linewhile-loop

解决方案


我怎样才能完成这项工作,因为一直退出 cmd 然后重新导航到我的文件真的很烦人。谢谢

不要使用裸except(except没有指定异常类型的语句):在 Python 中,Ctrl-C 被转换为异常并引发。这意味着except在没有更多信息的情况下捕获它,并执行您定义的任何异常处理代码。

在 Python 中,您几乎总是希望显式捕获Exception,因为它包含大多数异常,但重要的是排除KeyboardInterrupt(这是 Ctrl-C 转换为的内容)和SystemExit(这是sys.exit()触发的内容)。请参阅异常层次结构

对此的主要例外是执行清理然后直接重新引发,在这种情况下,可以接受裸露的例外(尽管通常是不必要的,因为如果进程被杀死,您通常不需要关闭文件等)。

顺便说一句,如果您需要定义自己的异常,这同样适用:它应该扩展Exception,除非它是通常不应该被捕获和恢复的系统类型异常。


推荐阅读