开发者

Keep Windows Console open after a Python Error

开发者 https://www.devze.com 2022-12-30 05:18 出处:网络
File associations on my machine (winxp home) are such that a python script is directly opened with the python interpreter. If I double click on a python script a console window runs and every thing is

File associations on my machine (winxp home) are such that a python script is directly opened with the python interpreter. If I double click on a python script a console window runs and every thing is fine - as long as there is no syntax error in the script.

In that case the console window opens up for a moment but it is closed immediately. Too fast to read the error message.

Of course their would be the possibility to manually open a console windo开发者_如何学编程w and to execute the script by typing python myscript.py but I am sure that there is a more convenient (i.e. "double click based") solution.


Make a batch file:

C:\Python26\python.exe %1
IF %ERRORLEVEL% NEQ 0 PAUSE

Use that as your file association instead of python.exe directly. This will only cause the PAUSE statement to execute if python.exe returns an error


The canonical way to run a command in a command prompt window that doesn't close is

cmd /k "your command"


The way that I do it is i right click the script that I saved from notepad to a .py file, then i click edit with IDLE, This is an editing thingy, but you can also run modules from it


I've left a comment at rossipedia's answer about a similar situation, but I doubt it's gonna get noticed in a 8 year old post. So, I've experimented myself.

I have a python script that processes a folder that's dropped on it. As I add new lines, sometimes I get syntax errors, and I can't view them because the command prompt window closes too quickly. In order to keep the window open after an error, I had to modify rossipedia's code. I needed a way to pass a path to the bat file (drop a folder on it) and make the bat pass that path to the python script. The following does that:

debug.bat:

@echo off

REM debug.bat and myscript.py should be in the same dir, otherwise use absolute path for the python script

C:\Users\%username%\AppData\Local\Programs\Python\Python36-32\python.exe "%~dp0\myscript.py" %1
IF %ERRORLEVEL% NEQ 0 PAUSE

myscript.py:

import sys
print("printing dropped file path:")
print(sys.argv[1])
input()

If I get an error, I just use the debug.bat to view the error, and it works the same (drop a folder on it).

Update:

In my actual python script, I have this line:

sys.path.append("modules")

This doesn't work when I use debug.bat. "modules" is a folder that's in the same folder with the python script. When the script is called with debug.bat, the current working directory changes to the dropped file's directory. So, to get the path to "modules", I had to use absolute path:

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "\\modules")
0

精彩评论

暂无评论...
验证码 换一张
取 消