簡體   English   中英

Python CTRL-C退出沒有回溯?

[英]Python CTRL-C exit without 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()

嘗試重構你的主循環; 更多的東西:

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")

你調用play()兩次,所以你需要將兩個 case放在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)

我已經糾正了其他兩個問題,這是更好地測試Noneis在Python,和你的第一個if測試是行不通的,因為next == "yes" or "y"被解釋為next == "yes""y" next == "yes"分開,與之間or之間。 "y"始終被視為True因此您永遠不會來到代碼中的其他分支。

請注意,我懷疑上面的代碼可以簡化得更多,但你根本沒有告訴我們你的play()函數,所以你讓我們猜測你想要做什么。

一個問題是,你需要附上您raw_input聲明在try except KeyboardInterrupt條款以及實際的play功能。 例如

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM