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


当前回答

如果您想从桌面快捷方式运行脚本,右键单击您的python文件并选择发送到|桌面(创建快捷方式)。然后右键单击快捷方式,选择“属性”。在“快捷方式”选项卡上选择“目标:”文本框,并在路径前面添加cmd /k,然后单击“确定”。快捷方式现在应该运行你的脚本,而不需要关闭,你不需要输入('按回车键关闭')

注意,如果你的机器上有多个版本的python,在cmd /k和scipt路径之间添加所需的python可执行文件的名称,如下所示:

cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"

其他回答

最简单的方法:

your_code()

while True:
   pass

当您打开窗口时,它不会关闭,直到您关闭提示符。

最简单的方法:

import time

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

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

Go here and download and install Notepad++ Go here and download and install Python 2.7 not 3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User") Close Powershell and reopen it. Make a directory for your programs. mkdir scripts Open that directory cd scripts In Notepad++, in a new file type: print "hello world" Save the file as hello.py Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there. At the Powershell prompt type: python hello.py

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

python.exe %1
@echo off
echo.
pause

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

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

无需更改任何Python脚本。

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

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

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

 raw_input("Press enter to exit;")

或者,在Python 3中:

input("Press enter to exit;")