首页 > 解决方案 > 从 CMD 打开 .py 文件和直接从文件资源管理器打开它有什么区别?

问题描述

我刚刚从 Eric Matthes 的《Python Crash Course: 2nd edition》一书中开始学习 Python。我正在使用 Windows。大多数时候,我通过在 Windows 文件资源管理器中双击它们来直接打开 .py 文件。

但是当我尝试以相同的方式运行以下程序时,我发现它在 while 循环停止时立即关闭了 cmd 窗口,即使它应该继续:

#7.10 Dream Vacation (Small exercise to test what I have learnt)

dream = {}    #empty dictionary to store user inputs.
while True: 
    name = input('Enter your name: ')    #the key input for dream dictionary
    place = input('Enter your dream vacation destination: ')    #value input
    dream[name] = place    #Adding the input key and value pair to dream{} dictionary.

    #if the user wants to stop entering new inputs and wants to see the output:
    repeat = input('Do you want another person to respond? (yes/no): ')
    if repeat == 'no':    #if the user enters 'no' then the while loops stops looping.
        break

print("\nHere are the poll results:")
for name, place in dream.items():
    print(f"{name} wants to visit {place}.")

但是,当我从 CMD(通过使用 cd 命令)正确打开它的传统方式运行相同的代码时,代码完全按照预期运行。

我很好奇为什么会发生这种情况。请让我知道您为什么认为这可能会发生。我愿意接受像你们这样更有经验的程序员的任何建议或指导!

标签: pythoncmdwhile-loop

解决方案


当你的程序结束while循环时,它实际上会打印内容并且程序退出,所以基本上它会这样做(打印文本)但你看不到它,因为程序退出并且控制台关闭,如果你通过CMD打开它当程序退出时,控制台不会关闭并且文本保持在屏幕上。


推荐阅读