繁体   English   中英

从 Bat 文件调用 Python 并获取返回代码

[英]Call Python From Bat File And Get Return Code

我正在寻找一种从批处理文件中调用 python 脚本并从 python 脚本中获取返回码的方法。 我知道令人困惑,但它基于当前使用的系统。 我会重新编写它,但这种方式会快得多。

所以:

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

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

windows shell 将返回码保存在ERRORLEVEL变量中:

python somescript.py
echo %ERRORLEVEL%

在 python 脚本中,您可以通过调用exit()退出脚本并设置返回值:

exit(15)

在旧版本的 python 中,您可能首先必须从sys模块导入exit()函数:

from sys import exit
exit(15)

尝试:

import os
os._exit(ret_value)

您还应该检查:

您可以为此尝试此批处理脚本:

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM