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


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

 raw_input("Press enter to exit;")

或者,在Python 3中:

input("Press enter to exit;")

你有几个选择:

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.


cmd /k是打开任何控制台应用程序(不仅仅是Python)的典型方式,其中控制台窗口在应用程序关闭后仍然存在。我能想到的最简单的方法是按下Win+R,键入cmd /k,然后拖放你想要的脚本到运行对话框。


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


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

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

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

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


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


为了保持窗口打开,我同意Anurag的观点,这就是我为简短的计算类型程序保持窗口打开所做的。

这只会显示一个没有文本的游标:

raw_input() 

下一个例子会给你一个明确的消息,程序已经完成,而不是等待程序内的另一个输入提示:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

注意! 在python 3中,没有raw_input(),只有 输入()。 (2)使用单引号表示字符串;否则,如果你在任何东西周围输入双精度,比如 "raw_input()",它会认为它是一个函数,变量等,而不是文本。

在下一个例子中,我使用双引号,但它不起作用,因为它认为“the”和“function”之间的引号中有一个断点,尽管当你阅读它时,你自己的大脑可以完全理解它:

print("You have reached the end and the "input()" function is keeping the window open")
input()

希望这能帮助到那些刚开始学习,还不知道计算机是如何思考的人。这可能需要一段时间。: o)


在出现异常时保持窗口打开(打印异常时)

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()

用下面两行代码创建一个Windows批处理文件:

python your-program.py

pause

除了input和raw_input,你还可以使用一个无限while循环,像这样: while True: pass (Python 2.5+/3)或while 1: pass(所有版本的Python 2/3)。不过,这可能需要计算能力。

还可以从命令行运行程序。在命令行中输入python (Mac OS X终端),它应该是python 3。(你的Python版本)如果它没有显示你的Python版本,或者说Python:命令没有找到,查看更改PATH值(环境值,上面列出)/输入C:\(Python文件夹\ Python .exe。如果成功,输入python或C:\(python安装)\python.exe和程序的完整目录。


在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)

使用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.

在windows 10上插入以下语句:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

奇怪,但对我很管用!(当然是和input()一起放在末尾)


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

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

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

Python 3

input('Press Enter to Exit...')

会成功的。


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

python.exe %1
@echo off
echo.
pause

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

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

无需更改任何Python脚本。

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

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


让窗户一直开着的简单方法:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

计数器是这样代码就不会重复自己。


你可以打开PowerShell,输入“python”。 导入Python之后,您可以从您最喜欢的文本编辑器中复制粘贴源代码来运行代码。

窗户关不上。


如果你想保持cmd-window打开并且在运行文件目录下,这在Windows 10下是有效的:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

最简单的方法:

import time

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

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


我发现在win10的py3环境上的解决方案只是以管理员身份运行cmd或powershell,输出将保持在相同的控制台窗口,任何其他类型的用户运行python命令将导致python打开一个新的控制台窗口。


你可以直接写

input()

在代码的末尾

因此,当你运行你的脚本时,它会等待你输入一些东西

{ENTER for example}

`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

只需在实际代码之后编写上面的代码。如。我从用户输入和打印在控制台,因此我的代码将看起来像这样->

`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

试试这个,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

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


你可以使用-i选项启动python,或者设置环境变量PYTHONINSPECT=x。从文档中可以看出:

运行脚本后进行交互检查;强制执行提示符甚至 如果stdin看起来不是终结符;还PYTHONINSPECT = x

所以当你的脚本崩溃或完成时,你会得到一个python提示符,你的窗口不会关闭。


最简单的方法:

your_code()

while True:
   pass

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


创建一个像dontClose()这样的函数或带有while循环的函数:

import time

def dontClose():
    n = 1
    while n > 0:
        n += 1
        time.sleep(n)
        

然后在代码之后运行函数。例如:

print("Hello, World!")
dontClose()