python 获取python程序的退出代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1491796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:23:45  来源:igfitidea点击:

get the exit code for python program

python

提问by phoenix24

I'm running a python program on WindowsXP. How can I obtain the exit code after my program ends?

我在 WindowsXP 上运行 python 程序。程序结束后如何获取退出码?

采纳答案by Dave Webb

From a Windows command line you can use:

从 Windows 命令行,您可以使用:

echo %ERRORLEVEL%

For example:

例如:

C:\work>python helloworld.py
Hello World!

C:\work>echo %ERRORLEVEL%
0

回答by Tarnschaf

How do you run the program?

你如何运行程序?

Exit in python with sys.exit(1)

使用 sys.exit(1) 在 python 中退出

If you're in CMD or a BAT file you can access the variable %ERRORLEVEL% to obtain the exit code.

如果您在 CMD 或 BAT 文件中,您可以访问变量 %ERRORLEVEL% 以获取退出代码。

For example (batch file):

例如(批处理文件):

IF ERRORLEVEL 1 GOTO LABEL

回答by Blauohr

You can also use python to start your python-program

你也可以使用 python 来启动你的 python 程序

import subprocess
import sys
retcode = subprocess.call([sys.executable, "myscript.py"])
print retcode

回答by David Sykes

If you want to use ERRORLEVEL (as opposed to %ERRORLEVEL%) to check for a specific exit valueuse

如果您想使用 ERRORLEVEL(而不是 %ERRORLEVEL%)来检查特定的退出值,请使用

IF ERRORLEVEL <N> IF NOT ERRORLEVEL <N+1> <COMMAND>

For example

例如

IF ERRORLEVEL 3 IF NOT ERRORLEVEL 4 GOTO LABEL