Python CTRL-C退出没有回溯?

时间:2012-09-17 19:54:40

标签: python python-2.7 exit traceback

为学习目的构建一个简单的“Rock,Paper,Scissors”Python游戏。

我已经阅读了一些关于退出Python而没有回溯的其他帖子。我正在尝试实现它,但仍然得到追溯!有些Python wiz可以指出这个Python假人有什么不对吗?想法是单击RETURN(或键入“yes”或“y”将使程序再次运行play(),但是按CTRL-C将关闭它而不进行回溯。我使用的是Python 2.7。

    # modules
    import sys, traceback
    from random import choice

    #set up our lists
    ROCK, PAPER, SCISSORS = 1, 2, 3
    names = 'ROCK', 'PAPER', 'SCISSORS'

    #Define a function for who beats who?
    def beats(a, b):
        return (a,b) in ((PAPER, ROCK), (SCISSORS, PAPER), (ROCK, SCISSORS))

    def play():
        print "Please select: "
        print "1 Rock"
        print "2 Paper"
        print "3 Scissors"
        # player choose Rock, Paper or Scissors
        player_choice = int(input ("Choose from 1-3: "))
        # assigns the CPU variable a random CHOICE from a list.
        cpu_choice = choice((ROCK, PAPER, SCISSORS))

        if cpu_choice != player_choice:
            if beats(player_choice, cpu_choice):
                print "You chose %r, and the CPU chose %r." % (names[player_choice - 1], names[cpu_choice - 1])
                print "You win, yay!!"
            else:
                print "You chose %r, and the CPU chose %r." % (names[player_choice - 1], names[cpu_choice - 1])
                print "You lose. Yuck!"
        else:
            print "You chose %r, and the CPU chose %r." % (names[player_choice - 1], names[cpu_choice - 1])
            print "It's a tie!"

        print "Do you want to play again? Click RETURN to play again, or CTRL-C to exit!"

        next = raw_input("> ")

        # THIS IS WHAT I'M WORKING ON - NEED TO REMOVE TRACEBACK!
        if next == "yes" or "y":
            try:
                play()
            except KeyboardInterrupt:
                print "Goodbye!"
            except Exception:
                traceback.print_exc(file=sys.stdout)
            sys.exit(0)
        elif next == None:
            play()
        else:
            sys.exit(0)

# initiate play() !
play()

3 个答案:

答案 0 :(得分:4)

尝试重构主循环;更多的东西:

try:
    while (play()):
        pass
except KeyboardInterrupt:
    sys.exit(0)

play看起来像:

def play():
    _do_play() # code for the actual game

    play_again = raw_input('play again? ')
    return play_again.strip().lower() in ("yes", "y")

答案 1 :(得分:3)

您拨打play()两次,因此您需要将两个案例放在try / except块中:

if next in ("yes", "y"):
    try:
        play()
    except KeyboardInterrupt:
        print "Goodbye!"
    except Exception:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)
elif next is None:
    try:
        play()
    except KeyboardInterrupt:
        print "Goodbye!"
    except Exception:
        traceback.print_exc(file=sys.stdout)
        sys.exit(0)
else:
    sys.exit(0)

我已经纠正了其他两个问题,最好在python中使用None测试is,并且您的第一个if测试无法正常工作,因为{{1 }}与next == "yes" or "y"分开解释为next == "yes",中间有"y"or始终被视为"y",因此您永远不会来到代码中的其他分支。

请注意,我怀疑上述代码可以简化得更多,但您根本没有向我们展示您的True功能,所以您让我们猜测您要做什么。

答案 2 :(得分:2)

一个问题是,您需要将raw_input语句括在try except KeyboardInterrupt子句以及实际的play函数中。 e.g。

try:
   nxt = raw_input('>')
   if nxt.lower().startswith('y') or (nxt.strip() == ''):
      play()
   else:
      sys.exit(0)
except KeyboardInterrupt:
   sys.exit(0)
except Exception:
   traceback.print_exc(file=sys.stdout)