简体   繁体   English

如何保持 Python 脚本 output window 打开?

[英]How to keep a Python script output window open?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away.我刚刚开始使用 Python。当我在 Windows 上执行 python 脚本文件时,output window 出现但立即消失。 I need it to stay there so I can analyze my output. How can I keep it open?我需要它留在那儿以便分析我的 output。我怎样才能让它保持打开状态?

You have a few options:你有几个选择:

  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.为此,您的路径中需要 python 可执行文件。 Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to).只需检查如何在 Windows 上编辑环境变量,并添加C:\PYTHON26 (或您将 python 安装到的任何目录)。

    When the program ends, it'll drop you back to the cmd prompt instead of closing the window.当程序结束时,它会让您回到cmd提示符,而不是关闭 window。

  2. Add code to wait at the end of your script.添加代码以在脚本末尾等待。 For Python2, adding...对于 Python2,添加...

     raw_input()

    ... at the end of the script makes it wait for the Enter key. ...在脚本的末尾让它等待Enter键。 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() .对于 Python3,使用input()

  3. Use an editor that pauses for you.使用为您暂停的编辑器。 Some editors prepared for python will automatically pause for you after execution.有些编辑为python准备的,执行完会自动给你暂停。 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.我发现在运行时将其配置为“ python -i myscript.py ”特别有用。 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.程序结束后,您将进入 python shell,加载程序环境,因此您可以进一步使用变量并调用函数和方法。

cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. cmd /k是使用控制台 window 打开任何控制台应用程序(不仅是 Python)的典型方法,该控制台将在应用程序关闭后保留。 The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.我能想到的最简单的方法是按 Win+R,键入cmd /k ,然后将您想要的脚本拖放到“运行”对话框中。

Start the script from an already open cmd window or at the end of the script add something like this, in Python 2:从已经打开的 cmd window 开始脚本,或者在脚本末尾添加类似这样的内容,在 Python 2 中:

 raw_input("Press enter to exit;")

Or, in Python 3:或者,在 Python 3 中:

input("Press enter to exit;")

To keep your window open in case of exception (yet, while printing the exception)在出现异常时保持 window 打开(但在打印异常时)

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

To keep the window open in any case:要在任何情况下保持 window 打开:

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 Python 3

For Python3 you'll have to use input() in place of raw_input() , and of course adapt the print statements.对于 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() 

To keep the window open in any case:要在任何情况下保持 window 打开:

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

you can combine the answers before: (for Notepad++ User)您可以结合之前的答案:(对于 Notepad++ 用户)

press F5 to run current script and type in command:按 F5 运行当前脚本并输入命令:

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

in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on:)通过这种方式,您在执行 Notepad++ python 脚本后保持交互模式,并且您可以使用变量等进行操作:)

Create a Windows batch file with these 2 lines:使用以下两行创建一个 Windows 批处理文件:

python your-program.py

pause

Using atexit , you can pause the program right when it exits.使用atexit ,您可以在程序退出时立即暂停它。 If an error/exception is the reason for the exit, it will pause after printing the stacktrace.如果错误/异常是退出的原因,它将在打印堆栈跟踪后暂停。

import atexit

# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')

In my program, I put the call to atexit.register in the except clause, so that it will only pause if something went wrong.在我的程序中,我atexit.register的调用放在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.

In python 2 you can do it with: raw_input()在 python 2 中,您可以使用:raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()在 python 3 你可以用: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)另外,你可以用 time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

On Python 3在 Python 3

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

Will do the trick.会成功的。

You can just write你可以只写

input()

at the end of your code在你的代码的末尾

therefore when you run you script it will wait for you to enter something因此,当您运行脚本时,它会等待您输入内容

{ENTER for example}

I had a similar problem.我有一个类似的问题。 With Notepad++ I used to use the command: C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.使用 Notepad++ 我曾经使用命令: C:\Python27\python.exe "$(FULL_CURRENT_PATH)"在代码终止后立即关闭 cmd window。
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.现在我正在使用cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)"使 cmd window 保持打开状态。

To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.为了让 window 保持打开状态,我同意 Anurag 的观点,这就是我为了让我的 windows 保持打开状态以用于简短的小计算类型程序。

This would just show a cursor with no text:这只会显示一个没有文本的 cursor:

raw_input() 

This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:下一个例子会给你一个明确的信息,表明程序已经完成,而不是等待程序中的另一个输入提示:

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

Note!笔记!
(1) In python 3, there is no raw_input() , just input() . (1) 在 python 3 中,没有raw_input() ,只有input()
(2) Use single quotes to indicate a string; (2)用单引号表示一个字符串; otherwise if you type doubles around anything, such as "raw_input()", it will think it is a function, variable, etc, and not text.否则,如果您在任何内容周围键入双打,例如“raw_input()”,它会认为它是 function、变量等,而不是文本。

In this next example, I use double quotes and it won't work because it thinks there is a break in the quotes between "the" and "function" even though when you read it, your own mind can make perfect sense of it:在下一个示例中,我使用了双引号,它不会起作用,因为它认为“the”和“function”之间的引号中有一个中断,即使当您阅读它时,您自己的头脑也能完全理解它:

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

Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet.希望这可以帮助其他可能刚起步但仍未弄清楚计算机如何思考的人。 It can take a while.这可能需要一段时间。 :o) :o)

If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut) .如果您想从桌面快捷方式运行脚本,请右键单击您的 python 文件和 select Send to|Desktop (create shortcut) Then right click the shortcut and select Properties.然后右键单击快捷方式和 select 属性。 On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK.在快捷方式选项卡 select 的目标:文本框中,在路径前添加cmd /k ,然后单击确定。 The shortcut should now run your script without closing and you don't need the input('Hit enter to close')快捷方式现在应该在不关闭的情况下运行你的脚本,你不需要input('Hit enter to close')

Note, if you have more than one version of python on your machine, add the name of the required python executable between cmd /k and the scipt path like this:请注意,如果您的计算机上有多个版本的 python,请在 cmd /k 和 scipt 路径之间添加所需的 python 可执行文件的名称,如下所示:

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

Apart from input and raw_input , you could also use an infinite while loop, like this: while True: pass (Python 2.5+/3) or while 1: pass (all versions of Python 2/3).除了inputraw_input之外,您还可以使用无限while循环,如下所示: while True: pass (Python 2.5+/3) 或while 1: pass (Python 2/3 的所有版本)。 This might use computing power, though.不过,这可能会使用计算能力。

You could also run the program from the command line.您也可以从命令行运行该程序。 Type python into the command line (Mac OS X Terminal) and it should say Python 3.?.?在命令行(Mac OS X 终端)中键入python ,它应该Python 3.?.? (Your Python version) It it does not show your Python version, or says python: command not found , look into changing PATH values (enviromentl values, listed above)/type C:\(Python folder\python.exe . If that is successful, type python or C:\(Python installation)\python.exe and the full directory of your program. (你的 Python 版本)它没有显示你的 Python 版本,或者说python: command not found ,查看更改 PATH 值(环境值,上面列出)/类型C:\(Python folder\python.exe 。如果是成功,键入pythonC:\(Python installation)\python.exe和程序的完整目录

A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:一个迟来的答案,但我创建了一个名为pythonbat.bat的 Windows 批处理文件,其中包含以下内容:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.然后将pythonbat.bat指定为.py文件的默认处理程序。

Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...现在,当我在文件资源管理器中双击一个.py文件时,它会打开一个新的控制台 window,运行 Python 脚本然后暂停(保持打开状态),直到我按下任意键......

No changes required to any Python scripts.无需更改任何 Python 脚本。

I can still open a console window and specify python myscript.py if I want to...我仍然可以打开控制台 window 并指定python myscript.py如果我想...

(I just noticed @maurizio already posted this exact answer) (我刚刚注意到@maurizio 已经发布了这个确切的答案)

If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:如果你想保持 cmd-window 打开并在运行文件目录中,这在 Windows 10 工作:

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

I found the solution on my py3 enviroment at win10 is just run cmd or powershell as Administrator,and the output would stay at the same console window,any other type of user run python command would cause python to open a new console window. I found the solution on my py3 enviroment at win10 is just run cmd or powershell as Administrator,and the output would stay at the same console window,any other type of user run python command would cause python to open a new console window.

The simplest way:最简单的方法:

your_code()

while True:
   pass

When you open the window it doesn't close until you close the prompt.当您打开 window 时,它不会关闭,直到您关闭提示。

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

simply write the above code after your actual code.只需在您的实际代码之后编写上面的代码。 for eg.例如。 am taking input from user and print on console hence my code will be look like this -->我正在从用户那里获取输入并在控制台上打印,因此我的代码将如下所示 -->

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

Try this,试试这个,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

This will only stop console window, not the IDLE.这只会停止控制台 window,而不是 IDLE。

You can launch python with the -i option or set the environment variable PYTHONINSPECT=x .您可以使用-i选项启动 python 或设置环境变量PYTHONINSPECT=x From the docs:从文档:

inspect interactively after running script;运行脚本后交互式检查; forces a prompt even if stdin does not appear to be a terminal;即使 stdin 看起来不是终端,也会强制提示; also PYTHONINSPECT=x还有 PYTHONINSPECT=x

So when your script crashes or finishes, you'll get a python prompt and your window will not close.因此,当您的脚本崩溃或完成时,您将收到 python 提示,而您的 window 将不会关闭。

Create a function like dontClose() or something with a while loop:创建一个 function 像dontClose()或带有while循环的东西:

import time

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

then run the function after your code.然后在你的代码之后运行 function。 for eg:例如:

print("Hello, World!")
dontClose()
  1. Go here and download and install Notepad++ Go这里下载安装Notepad++
  2. Go here and download and install Python 2.7 not 3. Go在这里下载并安装 Python 2.7 不是 3。
  3. Start, Run Powershell. Enter the following.开始,运行 Powershell。输入以下内容。 [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. Close Powershell and reopen it.关闭 Powershell 并重新打开它。
  5. Make a directory for your programs.为您的程序创建一个目录。 mkdir scripts mkdir 脚本
  6. Open that directory cd scripts打开该目录 cd 脚本
  7. In Notepad++, in a new file type: print "hello world"在 Notepad++ 中,在一个新的文件类型中: print "hello world"
  8. Save the file as hello.py将文件保存为 hello.py
  9. Go back to powershell and make sure you are in the right directory by typing dir. Go 回到 powershell 并通过键入 dir 确保您在正确的目录中。 You should see your file hello.py there.你应该在那里看到你的文件 hello.py。
  10. At the Powershell prompt type: python hello.py在 Powershell 提示符下键入: python hello.py

On windows 10 insert at beggining this:在 windows 10 开头插入:

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

Strange, but it work for me,(Together with input() at the end, of course)奇怪,但它对我有用,(当然还有最后的 input() )

You can open PowerShell and type "python".您可以打开 PowerShell 并输入“python”。 After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.导入 Python 后,您可以从您喜欢的文本编辑器中复制粘贴源代码以运行代码。

The window won't close. window 不会关闭。

A simple hack to keep the window open:保持 window 打开的简单技巧:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won't repeat itself.计数器是为了使代码不会重复。

The simplest way:最简单的方法:

import time

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

this will leave the code up for 1 minute then close it.这将使代码保留 1 分钟,然后将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM