为了简化,我有运行多个 python 程序的批处理文件:
start "01" /wait "C:\python27\python.exe" test1.py
start "02" /wait "C:\python27\python.exe" test2.py
但我发现即使 test1.py 由于错误而没有运行,它也会继续运行 test2.py。
一旦遇到该错误,它甚至会立即关闭 test1.py 的窗口,并为 test2.py 创建另一个窗口
当然,如果我通过运行单独运行test1.py
python test1.py
然后它会打印所有错误消息。
由于我在一批中有数十个 python 文件,因此很难知道其中哪一个导致了错误,而且我什至不知道错误是什么,因为我看不到错误消息。
当遇到错误时,如何让它停止(但不关闭窗口),并显示错误消息?
最佳答案
我对Python了解不多。但根据问题,它会将消息输出到 stdout 和 stderr,只有控制台应用程序才会这样做。
但是,如果 python.exe
确实是控制台应用程序而不是 Windows (GUI) 应用程序,则实际上没有必要使用 start "title"/wait
作为这只会导致在单独的命令行解释器进程中调用控制台应用程序python.exe
,这就是为什么命令行解释器进程中没有显示python.exe
的输出其中执行批处理文件。
我建议简单地尝试一下:
@echo off
echo Calling Python with script test1.py.
"C:\python27\python.exe" test1.py
if errorlevel 1 pause
echo Calling Python with script test2.py.
"C:\python27\python.exe" test2.py
if errorlevel 1 pause
有关错误处理,请参见示例:
- Exit codes in Python
- get the exit code for python program
- Testing for a Specific Error Level in Batch Files
- Correct Testing Precedence of Batch File ERRORLEVELs
- 命令的 Windows 文档 If
请使用帮助页面 How do I search? 上解释的 Stack Overflow 搜索功能还有 WWW 搜索引擎。您肯定没有做任何其他 Python 用户尚未做过的事情,因此也很可能经常被问到。
我们希望提问者尝试自己找到解决方案,而不是要求其他人完成他们的工作,请参阅帮助页面 What topics can I ask about here?
关于python - 批处理运行时显示或留下 python 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24695454/