【问题标题】:Call Python From Bat File And Get Return Code从 Bat 文件调用 Python 并获取返回码
【发布时间】:2009-06-18 15:11:43
【问题描述】:

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

所以:

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

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

【问题讨论】:

    标签: python batch-file


    【解决方案1】:

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

    python somescript.py
    echo %ERRORLEVEL%
    

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

    exit(15)
    

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

    from sys import exit
    exit(15)
    

    【讨论】:

    • Errorlevel 只是一个伪变量,它实际上并不存在于环境中的任何位置。
    • 如果 %ERRORLEVEL% 变量已经存在,这将不起作用。在这种情况下,Python 不会覆盖它(但会返回正确的代码 - 它只会被变量隐藏!)。
    • @fmuecke 我不明白你的意思。我使用 %ERRORLEVEL% 捕获来自不同 python 调用的返回。来自不同 python 脚本的 %ERRORLEVEL% 的不同值
    【解决方案2】:

    试试:

    import os
    os._exit(ret_value)
    

    您还应该检查:

    【讨论】:

    • 多亏了你,你的两个答案都是正确的,我只需要从 bat 文件中得到它的另一面。再次感谢。
    • 我更喜欢使用sys.exit()。例如,在编写要在 Visual Studio 构建过程上运行的脚本时,您希望在“构建输出”窗口上显示脚本输出。 os._exit() 命令不允许您查看 python 的“stdout”。 底线:在某些情况下,sys.exit() 可能比os._exit() 更健壮。每当一个人的行为不符合预期时,请考虑使用另一种方法。
    【解决方案3】:

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

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2011-02-20
      • 2013-10-24
      • 2016-01-06
      相关资源
      最近更新 更多