问题:如何保持Python脚本输出窗口打开?

我刚开始使用Python。当我在Windows上执行python脚本文件时,出现输出窗口,但立即消失。我需要它呆在那里,以便我可以分析我的输出。如何保持打开状态?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?


回答 0

您有几种选择:

  1. 从已经打开的终端运行程序。打开命令提示符并键入:

    python myscript.py

    为此,您需要在路径中使用python可执行文件。只需检查如何在Windows 上编辑环境变量,然后添加C:\PYTHON26(或安装python的任何目录)即可。

    程序结束后,它将带您回到cmd提示符,而不是关闭窗口。

  2. 添加代码以在脚本末尾等待。对于Python2,添加…

    raw_input()

    …在脚本末尾使其等待Enter键。该方法很烦人,因为您必须修改脚本,并且必须记得在完成后将其删除。测试其他人的脚本时特别烦人。对于Python3,请使用input()

  3. 使用适合您的编辑器。一些为python准备的编辑器将在执行后自动为您暂停。其他编辑器允许您配置用于运行程序的命令行。我发现python -i myscript.py在运行时将其配置为“ ” 特别有用。程序结束后,您将在加载了程序环境的情况下进入python shell,因此您可以进一步使用变量以及调用函数和方法。

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

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

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


回答 1

cmd /k是使用控制台窗口打开任何控制台应用程序(不仅限于Python)的典型方法,该窗口在应用程序关闭后仍将保留。我认为最简单的方法是按Win + R,键入cmd /k,然后将想要的脚本拖放到“运行”对话框中。

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


回答 2

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

 raw_input("Press enter to exit ;)")

或者,在Python 3中:

input("Press enter to exit ;)")

Start the script from already open cmd window or at the end of script add something like this, in Python 2:

 raw_input("Press enter to exit ;)")

Or, in Python 3:

input("Press enter to exit ;)")

回答 3

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

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,您必须,当然还要修改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()

To keep your window open in case of exception (yet, while printing the exception)

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:

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

For Python3 you’ll have to , and of course adapt the print statements.

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:

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

回答 4

您可以在之前合并答案:(对于Notepad ++用户)

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

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

这样,您在执行Notepad ++ python脚本后就可以保持交互模式,并且可以使用变量等等:)

you can combine the answers before: (for Notepad++ User)

press F5 to run current script and type in command:

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


回答 5

使用以下两行创建Windows批处理文件:

python your-program.py

pause

Create a Windows batch file with these 2 lines:

python your-program.py

pause

回答 6

在python 2中,您可以执行以下操作:raw_input()

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

在python 3中,您可以执行以下操作:input()

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

另外,您可以使用time.sleep(time)

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

In python 2 you can do it with: raw_input()

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

In python 3 you can do it with: input()

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

Also, you can do it with the time.sleep(time)

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

回答 7

使用atexit,您可以在程序退出时立即暂停它。如果错误/异常是退出的原因,则它将在打印stacktrace后暂停。

import atexit

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

在我的程序中,我将对的调用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.

Using atexit, you can pause the program right when it exits. 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.

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.

回答 8

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

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.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.


回答 9

在Python 3上

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

会成功的。

On Python 3

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

Will do the trick.


回答 10

为了保持窗口打开,我同意Anurag的意见,这就是我为简短的小型计算类型程序保持窗口打开的方法。

这只会显示没有文本的光标:

raw_input() 

下一个示例将向您清楚地表明该程序已完成,而不必等待该程序中的另一个输入提示:

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

注意!
(1)在python 3中,没有raw_input(),只有 input()
(2)用单引号表示一个字符串;否则,如果您在任何内容(例如“ raw_input()”)附近键入double,它将认为它是函数,变量等,而不是文本。

在下一个示例中,我使用双引号,但由于它认为“ the”和“ function”之间的引号存在中断,所以即使它在您阅读时,您自己的想法也可以完全理解,但它不会起作用:

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

希望这可以帮助那些可能刚起步但还没有弄清楚计算机如何思考的人。可能要花一点时间。:o)

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.

This would just show a cursor with no text:

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().
(2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as “raw_input()”, it will think it is a function, variable, etc, and not text.

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:

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)


回答 11

如果要从桌面快捷方式运行脚本,请右键单击python文件,然后选择Send to|Desktop (create shortcut)。然后右键单击快捷方式,然后选择“属性”。在“快捷方式”选项卡上,选择“目标:”文本框,然后添加cmd /k 到路径的前面,然后单击“确定”。现在,该快捷方式应该可以在不关闭脚本的情况下运行您的脚本,并且您不需要input('Hit enter to close')

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

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

If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut). Then right click the shortcut and select Properties. On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK. The shortcut should now run your script without closing and you don’t need the 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:

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

回答 12

除了input和之外raw_input,您还可以使用无限while循环,例如: while True: pass(Python 2.5 + / 3)或while 1: pass(Python 2/3的所有版本)。但是,这可能会使用计算能力。

您也可以从命令行运行程序。python在命令行(Mac OS X Terminal)中键入,然后说Python 3.?.?(您的Python版本)它不会显示您的Python版本,或者说您python: command not found正在研究更改PATH值(上面列出的环境值)/ type C:\(Python folder\python.exe。如果成功,则键入pythonC:\(Python installation)\python.exe和程序的完整目录

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


回答 13

答案很迟,但是我创建了一个Windows Batch文件pythonbat.bat,该文件包含以下内容:

python.exe %1
@echo off
echo.
pause

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

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

无需更改任何Python脚本。

我仍然可以打开控制台窗口并指定python myscript.py是否要…

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

A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.

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…

No changes required to any Python scripts.

I can still open a console window and specify python myscript.py if I want to…

(I just noticed @maurizio already posted this exact answer)


回答 14

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

窗户不会关闭。

You can open PowerShell and type “python”. After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.

The window won’t close.


回答 15

如果要保持cmd窗口打开并位于运行文件目录中,则可以在Windows 10上运行:

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

If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:

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

回答 16

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

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.


回答 17

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

回答 18

保持窗口打开的简单技巧:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

计数器是这样,因此代码不会重复自身。

A simple hack to keep the window open:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won’t repeat itself.


回答 19

最简单的方法:

import time

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

这将使代码保留1分钟,然后将其关闭。

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.


回答 20

在Windows 10上插入以下代码:

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

奇怪,但是对我有用!(当然,最后还有input())

On windows 10 insert at beggining this:

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

Strange, but it work for me!(Together with input() at the end, of course)


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。