停止关闭Python窗口的问题

时间:2019-05-30 14:34:15

标签: python python-3.x pycharm

这是一个很小且非常基本的程序/游戏。在代码结束之前,我无法正常关闭Python终端。但是在PyCharm IDE中,当我运行代码时,程序运行良好,并且只有在执行了所有代码并且已经从用户输入了输入后,程序才结束。我不知道是否是因为编程背后的逻辑,我对此还是很陌生,所以我知道这可能是问题所在。

我尝试使用输入来防止窗口关闭。

input("\nPress any key to exit... ")

就像我之前说过的那样,这似乎可以在IDE中使用,但是当直接从.py文件中运行程序时却无法使用

不想要通过CMD或批处理文件来运行程序。我希望用户能够通过简单地按Pycharm文件并通过其相应控制台运行它来运行游戏。

以下是代码:

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


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

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


scoreList = open("Score.txt", "a",)
scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
scoreList = open("Score.txt", "r")
print("\nHere is your score list :")
for line in scoreList:
    line = line.strip()
    find = line.find(playerName)
    if find >0:
        lineNumber += 1
        score = line[line.rfind(" ")+1:]
        print("Attempt #{0} | Score: {1}".format(lineNumber, score))
input("\nPress any key to exit... ")


scoreList.close()

PyCharm IDE会运行该程序直到结束(打印尝试次数和记分牌,然后等待用户输入退出)。 这是我希望通过Python的控制台运行应用程序时发生的事情。

编辑: 如果我通过批处理文件通过CMD运行程序,也是如此,如果可能的话,我仍然希望避免这种情况

到目前为止,只要用户猜到正确的数字,Python的控制台就会关闭,而不会等待用户输入的退出。我猜想该程序仍会打印尝试次数和玩家的记分牌,但控制台关闭得太快,用户看不到这些行。

1 个答案:

答案 0 :(得分:0)

好吧,所以我在整个乐谱读取代码周围添加了try-except块,我设法抓住了一个错误。但是,我认为可能特定于我自己的Python 3安装,因此您应该使用相同的方法并查看可能存在的问题。

就我而言,Python 2安装在C:\中,而Python 3安装在(出于某种原因)C:\Users\username\AppData\Local\Programs\Python\Python36中。当我运行您的代码时,它默认情况下是使用Python2打开的,并且工作正常。它按预期创建并从Scores.txt读取。

但是当我手动使用Python3时,它总是与[Errno 13] Permission denied: 'Score.txt'一起崩溃,这是一个权限问题。您可能会明白为什么我认为这是由于我现在的安装位置所致。

无论如何,您可以使用下面的代码来希望打印错误消息。一旦有了这些,就很容易修复可能的错误。其余代码(包括此后的input调用)应保持不变。

try:
    scoreList = open("Score.txt", "a",)
    scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
    scoreList = open("Score.txt", "r")
    print("\nHere is your score list :")
    for line in scoreList:
        line = line.strip()
        find = line.find(playerName)
        if find >0:
            lineNumber += 1
            score = line[line.rfind(" ")+1:]
            print("Attempt #{0} | Score: {1}".format(lineNumber, score))
except Exception as e:
    print(e)