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


当前回答

Python 3

input('Press Enter to Exit...')

会成功的。

其他回答

你有几个选择:

Run the program from an already-open terminal. Open a command prompt and type: python myscript.py For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to). When the program ends, it'll drop you back to the cmd prompt instead of closing the window. Add code to wait at the end of your script. For Python2, adding ... raw_input() ... at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use input(). Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "python -i myscript.py" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.

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

 raw_input("Press enter to exit;")

或者,在Python 3中:

input("Press enter to exit;")

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

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
`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()`

在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)