我刚刚开始学习Python。当我在Windows上执行一个python脚本文件时,输出窗口出现但立即消失。我需要它停留在那里,这样我就可以分析我的输出。我怎么才能让它一直开着?
当前回答
用下面两行代码创建一个Windows批处理文件:
python your-program.py
pause
其他回答
创建一个像dontClose()这样的函数或带有while循环的函数:
import time
def dontClose():
n = 1
while n > 0:
n += 1
time.sleep(n)
然后在代码之后运行函数。例如:
print("Hello, World!")
dontClose()
你可以使用-i选项启动python,或者设置环境变量PYTHONINSPECT=x。从文档中可以看出:
运行脚本后进行交互检查;强制执行提示符甚至 如果stdin看起来不是终结符;还PYTHONINSPECT = x
所以当你的脚本崩溃或完成时,你会得到一个python提示符,你的窗口不会关闭。
cmd /k是打开任何控制台应用程序(不仅仅是Python)的典型方式,其中控制台窗口在应用程序关闭后仍然存在。我能想到的最简单的方法是按下Win+R,键入cmd /k,然后拖放你想要的脚本到运行对话框。
你有几个选择:
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.
一个非常迟的回答,但我创建了一个名为pythonbat.bat的Windows批处理文件,其中包含以下内容:
python.exe %1
@echo off
echo.
pause
然后指定pythonbat.bat作为.py文件的默认处理程序。
现在,当我在文件资源管理器中双击一个.py文件时,它会打开一个新的控制台窗口,运行Python脚本,然后暂停(保持打开),直到我按下任何键……
无需更改任何Python脚本。
我仍然可以打开一个控制台窗口,并指定python myscript.py,如果我想…
(我刚刚注意到@maurizio已经发布了这个确切的答案)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 我如何找到哪个程序正在使用端口80在Windows?
- 使用try和。Python中的if