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


当前回答

试试这个,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

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

其他回答

在出现异常时保持窗口打开(打印异常时)

Python 2

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
        print "Press Enter to continue ..." 
        raw_input() 

在任何情况下保持窗户开着:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
    finally:
        print "Press Enter to continue ..." 
        raw_input()

Python 3

对于Python3,你必须使用input()来代替raw_input(),当然还要调整print语句。

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
        print("Press Enter to continue ...")
        input() 

在任何情况下保持窗户开着:

if __name__ == '__main__':
    try:
        ## your code, typically one function call
except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Press Enter to continue ...")
    input()

最简单的方法:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

这将使代码保持1分钟,然后关闭它。

`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

只需在实际代码之后编写上面的代码。如。我从用户输入和打印在控制台,因此我的代码将看起来像这样->

`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

为了保持窗口打开,我同意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)

你可以打开PowerShell,输入“python”。 导入Python之后,您可以从您最喜欢的文本编辑器中复制粘贴源代码来运行代码。

窗户关不上。