gpt4 book ai didi

Python CTRL-C 退出没有回溯?

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:04 27 4
gpt4 key购买 nike

构建一个简单的“石头剪刀布”Python 游戏以供学习。

我在这里阅读了其他一些关于在没有回溯的情况下退出 Python 的帖子。我正在尝试实现它,但仍然得到回溯!一些 Python 高手可以指出这个 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")

关于Python CTRL-C 退出没有回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com