我刚刚开始学习Python。当我在Windows上执行一个python脚本文件时,输出窗口出现但立即消失。我需要它停留在那里,这样我就可以分析我的输出。我怎么才能让它一直开着?


当前回答

在python 2中,你可以使用:raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

在python 3中,你可以使用:input()

>>print("Hello world!")    
>>input('Waiting a key...')

你也可以用时间。sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

其他回答

如果你想保持cmd-window打开并且在运行文件目录下,这在Windows 10下是有效的:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

使用atexit,你可以在程序退出时暂停它。如果一个错误/异常是退出的原因,它将在打印堆栈跟踪后暂停。

import atexit

# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')

在我的程序中,我调用了atexit。在except子句中注册,这样它只会在出现错误时暂停。

if __name__ == "__main__":
    try:
        something_that_may_fail()

    except:
        # Register the pause.
        import atexit
        atexit.register(input, 'Press Enter to continue...')

        raise # Reraise the exception.

试试这个,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

这只会停止控制台窗口,而不是IDLE窗口。

为了保持窗口打开,我同意Anurag的观点,这就是我为简短的计算类型程序保持窗口打开所做的。

这只会显示一个没有文本的游标:

raw_input() 

下一个例子会给你一个明确的消息,程序已经完成,而不是等待程序内的另一个输入提示:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

注意! 在python 3中,没有raw_input(),只有 输入()。 (2)使用单引号表示字符串;否则,如果你在任何东西周围输入双精度,比如 "raw_input()",它会认为它是一个函数,变量等,而不是文本。

在下一个例子中,我使用双引号,但它不起作用,因为它认为“the”和“function”之间的引号中有一个断点,尽管当你阅读它时,你自己的大脑可以完全理解它:

print("You have reached the end and the "input()" function is keeping the window open")
input()

希望这能帮助到那些刚开始学习,还不知道计算机是如何思考的人。这可能需要一段时间。: o)

从已经打开的cmd窗口或启动脚本 在Python 2中,在脚本的末尾添加如下内容:

 raw_input("Press enter to exit;")

或者,在Python 3中:

input("Press enter to exit;")