我刚刚开始学习Python。当我在Windows上执行一个python脚本文件时,输出窗口出现但立即消失。我需要它停留在那里,这样我就可以分析我的输出。我怎么才能让它一直开着?
当前回答
在出现异常时保持窗口打开(打印异常时)
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()
其他回答
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
试试这个,
import sys
stat='idlelib' in sys.modules
if stat==False:
input()
这只会停止控制台窗口,而不是IDLE窗口。
使用atexit,你可以在程序退出时暂停它。如果一个错误/异常是退出的原因,它将在打印堆栈跟踪后暂停。
import atexit
# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')
在我的程序中,我调用了atexit。在except子句中注册,这样它只会在出现错误时暂停。
if __name__ == "__main__":
try:
something_that_may_fail()
except:
# Register the pause.
import atexit
atexit.register(input, 'Press Enter to continue...')
raise # Reraise the exception.
最简单的方法:
import time
#Your code here
time.sleep(60)
#end of code (and console shut down)
这将使代码保持1分钟,然后关闭它。
用下面两行代码创建一个Windows批处理文件:
python your-program.py
pause
推荐文章
- 使用Conda进行批量包更新
- Ipython笔记本清除单元格输出代码
- ImportError: numpy.core.multiarray导入失败
- 有办法在Python中使用PhantomJS吗?
- 如何在Python中将if/else压缩成一行?
- 如何在Python 3中使用pip。Python 2.x
- 如何让IntelliJ识别常见的Python模块?
- Django:“projects”vs“apps”
- 如何列出导入的模块?
- 转换Python程序到C/ c++代码?
- 如何从gmtime()的时间+日期输出中获得自epoch以来的秒数?
- 在python模块文档字符串中放入什么?
- 我如何在Django中过滤一个DateTimeField的日期?
- 在Python中用索引迭代列表
- -e,——editable选项在pip install中什么时候有用?