How to Return a Value from Python in a Batch Script?

Estimated read time 2 min read

To return a value from a Python script to a Batch script, you can use the sys.exit() function in your Python script to exit with a specific exit code, which can then be captured in the Batch script. Here’s an example:

Python script (example.py):

import sys

def get_result():
    # Perform some computations
    result = 42
    return result

# Call the function and retrieve the result
result = get_result()

# Return the result as the exit code
sys.exit(result)

Batch script (example.bat):

@echo off

REM Run the Python script
python example.py

REM Capture the exit code from the Python script
set result=%errorlevel%

REM Print the captured result
echo Result: %result%

In this example, the Python script example.py defines a function get_result() that performs some computations and returns a result. The sys.exit(result) line exits the script with the provided result value as the exit code.

The Batch script example.bat runs the Python script using the python command. After the Python script completes, the %errorlevel% variable captures the exit code, which is stored in the result variable. Finally, the captured result is printed using echo.

By using the sys.exit() function and capturing the exit code in the Batch script, you can pass a value from your Python script back to the Batch script. Adjust the example code as needed based on your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply