我刚刚开始学习Python。当我在Windows上执行一个python脚本文件时,输出窗口出现但立即消失。我需要它停留在那里,这样我就可以分析我的输出。我怎么才能让它一直开着?
当前回答
在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)
其他回答
cmd /k是打开任何控制台应用程序(不仅仅是Python)的典型方式,其中控制台窗口在应用程序关闭后仍然存在。我能想到的最简单的方法是按下Win+R,键入cmd /k,然后拖放你想要的脚本到运行对话框。
最简单的方法:
import time
#Your code here
time.sleep(60)
#end of code (and console shut down)
这将使代码保持1分钟,然后关闭它。
你有几个选择:
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.
使用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.
创建一个像dontClose()这样的函数或带有while循环的函数:
import time
def dontClose():
n = 1
while n > 0:
n += 1
time.sleep(n)
然后在代码之后运行函数。例如:
print("Hello, World!")
dontClose()
推荐文章
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)
- 如何删除熊猫数据帧的最后一行数据
- 我如何在熊猫中找到数字列?
- 检查pandas数据框架索引中是否存在值