从批处理文件调用Python并获取返回码

17 投票
3 回答
31784 浏览
提问于 2025-04-15 12:20

我想找个方法,从一个批处理文件里调用一个Python脚本,并且能获取这个Python脚本的返回代码。我知道这听起来有点复杂,但这是基于一个正在使用的系统。我本来可以重写它,但这样做会快得多。

所以:

Bat ---------------------> Python
     * call python file *

Bat <--------------------------------- Python
      * python does a load of work *
      * and returns a return code  *

3 个回答

0

你可以试试这个批处理脚本:

@echo off

REM     %1 - This is the parameter we pass with the desired return code for the Python script that will be captured by the ErrorLevel env. variable.  
REM     A value of 0 is the default exit code, meaning it has all gone well. A value greater than 0 implies an error
REM     and this value can be captured and used for any error control logic and handling within the script
   
set ERRORLEVEL=
set RETURN_CODE=%1

echo (Before Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]
echo.

call python -c "import sys; exit_code = %RETURN_CODE%; print('(Inside python script now) Setting up exit code to ' + str(exit_code)); sys.exit(exit_code)"

echo.
echo (After Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]
echo.

然后当你用不同的返回代码值运行它几次时,你会看到预期的效果:

PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 5

(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ]

(Inside python script now) Setting up exit code to 5

(After Python script run) ERRORLEVEL VALUE IS: [ 5 ]

PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 3

(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ]

(Inside python script now) Setting up exit code to 3

(After Python script run) ERRORLEVEL VALUE IS: [ 3 ]

PS C:\Scripts\ScriptTests
3

试试这个:

import os
os._exit(ret_value)

你还应该检查一下:

23

Windows的命令行会把返回的结果代码保存在一个叫做 ERRORLEVEL 的变量里:

python somescript.py
echo %ERRORLEVEL%

在Python脚本中,你可以通过调用 exit() 来结束脚本并设置返回值:

exit(15)

在旧版本的Python中,你可能需要先从 sys 模块导入 exit() 函数:

from sys import exit
exit(15)

撰写回答