How to keep a Python script output window open?

2019-01-01 02:01发布

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?

17条回答
深知你不懂我心
2楼-- · 2019-01-01 02:42

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)

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 02:44

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)
查看更多
泛滥B
4楼-- · 2019-01-01 02:46

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.

查看更多
笑指拈花
5楼-- · 2019-01-01 02:50

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)

查看更多
笑指拈花
6楼-- · 2019-01-01 02:51

On Python 3

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

Will do the trick.

查看更多
骚的不知所云
7楼-- · 2019-01-01 02:54

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"
查看更多
登录 后发表回答