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


当前回答

一个非常迟的回答,但我创建了一个名为pythonbat.bat的Windows批处理文件,其中包含以下内容:

python.exe %1
@echo off
echo.
pause

然后指定pythonbat.bat作为.py文件的默认处理程序。

现在,当我在文件资源管理器中双击一个.py文件时,它会打开一个新的控制台窗口,运行Python脚本,然后暂停(保持打开),直到我按下任何键……

无需更改任何Python脚本。

我仍然可以打开一个控制台窗口,并指定python myscript.py,如果我想…

(我刚刚注意到@maurizio已经发布了这个确切的答案)

其他回答

试试这个,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

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

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

 raw_input("Press enter to exit;")

或者,在Python 3中:

input("Press enter to exit;")

我也遇到过类似的问题。在notepad++中,我曾经使用命令:C:\Python27\python.exe "$(FULL_CURRENT_PATH)"在代码终止后立即关闭cmd窗口。 现在我使用cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)"它保持cmd窗口打开。

你有几个选择:

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.

你可以组合答案之前:(notepad++用户)

按F5运行当前脚本并输入命令:

cmd /k python -i "$(FULL_CURRENT_PATH)"

这样,在执行notepad++ python脚本后,您将保持在交互模式,并且您能够使用您的变量等等:)