You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序直接运行时终端意外关闭问题求助

解决猜数字游戏双击运行时窗口闪退的问题

嘿,我完全懂你的困扰——PyCharm里运行游戏一切正常,能看完结果、等你按回车才退出,但直接双击.py文件时,刚猜对数字窗口就秒关,连得分榜都来不及看。咱们一步步搞定这个问题:

第一步:修复代码里的文件操作隐患

你的代码里连续打开了两次Score.txt,但第一次打开的文件句柄没关闭,这可能导致写入的内容还留在内存缓冲区,没及时存到磁盘,甚至干扰后续的读取操作。咱们用Python的with语句来处理文件,它会自动帮我们关闭文件,既安全又省心:

替换原来的文件读写部分:

# 写入玩家得分到文件
with open("Score.txt", "a") as score_file:
    score_file.write(f"Player: {playerName} | Guesses: {inputCounter}\n")

# 读取并显示当前玩家的历史得分
print("\nHere is your score list :")
lineNumber = 0
with open("Score.txt", "r") as score_file:
    for line in score_file:
        line = line.strip()
        if playerName in line:
            lineNumber += 1
            # 用split提取得分,比rfind更直观
            score = line.split(" ")[-1]
            print(f"Attempt #{lineNumber} | Score: {score}")

第二步:解决窗口闪退的核心问题

即使加了input(),Windows下双击运行有时还是会闪退,这通常是因为输出缓冲区没来得及刷新,或者程序隐藏了小错误导致提前崩溃。咱们做两个优化:

1. 强制刷新输出缓冲区

在最后的等待输入语句前,先强制刷新所有输出内容,确保它们都显示在窗口里:

import sys

# ... 你的游戏逻辑代码 ...

# 强制刷新所有输出,避免内容还在缓冲区就关闭窗口
sys.stdout.flush()
input("\nPress any key to exit... ")

2. 添加异常处理,避免程序崩溃

如果玩家输入了非数字内容(比如字母),你的代码会直接报错崩溃,导致窗口瞬间关闭。咱们给输入部分加个异常捕获:

while playerNumber != randomNumber:
    try:
        playerNumber = int(input("Please guess a whole number from 1 to 100: "))
    except ValueError:
        print("Oops! Please enter a valid whole number, try again.")
        continue
    inputCounter += 1
    if playerNumber < randomNumber:
        print("The number you have entered is LOWER than the generated number, please try again!")
    elif playerNumber > randomNumber:
        print("The number you have entered is HIGHER than the generated number, please try again!")

完整修改后的代码

把这些优化整合起来,最终代码如下:

import random
import sys

inputCounter = 0
lineNumber = 0
playerNumber = 0
randomNumber = random.randint(1, 100)
playerName = input("Please enter your name: ")

while playerNumber != randomNumber:
    try:
        playerNumber = int(input("Please guess a whole number from 1 to 100: "))
    except ValueError:
        print("Oops! Please enter a valid whole number, try again.")
        continue
    inputCounter += 1
    if playerNumber < randomNumber:
        print("The number you have entered is LOWER than the generated number, please try again!")
    elif playerNumber > randomNumber:
        print("The number you have entered is HIGHER than the generated number, please try again!")

print()
if inputCounter > 1:
    print(f"You won with {inputCounter} guesses")
else:
    print("CONGRATS! You won with 1 guess!!")

# 写入玩家得分
with open("Score.txt", "a") as score_file:
    score_file.write(f"Player: {playerName} | Guesses: {inputCounter}\n")

# 读取并展示历史得分
print("\nHere is your score list :")
lineNumber = 0
with open("Score.txt", "r") as score_file:
    for line in score_file:
        line = line.strip()
        if playerName in line:
            lineNumber += 1
            score = line.split(" ")[-1]
            print(f"Attempt #{lineNumber} | Score: {score}")

# 确保所有内容显示后再等待用户输入
sys.stdout.flush()
input("\nPress any key to exit... ")

这样修改后,双击.py文件运行游戏,窗口就会在显示完所有结果后,等你按任意键再关闭,和PyCharm里的体验完全一致啦!

内容的提问来源于stack exchange,提问作者Nikolas Desforges

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:56:23