Windows环境下Python subprocess返回Shell脚本错误退出码问题
Hey there! I totally get the frustration when something works perfectly in the terminal but not through Python—let's get this sorted out.
The root of your problem is that on Windows, simply calling your .sh script directly via subprocess doesn't use Git Bash's bash interpreter by default. Instead, Windows might treat the script as a regular file (like opening it in an editor) or use a different shell that doesn't properly execute your exit code logic, hence returning 0 every time.
Here's how to fix it:
Step 1: Locate Git Bash's bash.exe
First, find where your Git Bash installs bash.exe. It's usually in one of these paths:
C:\Program Files\Git\bin\bash.exe(64-bit Git)C:\Program Files (x86)\Git\bin\bash.exe(32-bit Git)
You can verify this by opening Command Prompt and running the path—if it launches Git Bash, you've got the right one.
Step 2: Update Your Python Code to Use bash.exe
Instead of calling the .sh script directly, tell subprocess to run it through Git Bash's bash executable. Here's a working example:
import subprocess # Replace with your actual bash.exe path bash_executable = "C:/Program Files/Git/bin/bash.exe" # Use the full path to your script if it's not in Python's working directory script_path = "./return_value.sh" # Run the script via bash result = subprocess.run([bash_executable, script_path]) # Print the exit code—this should now show 9! print(f"Script exit code: {result.returncode}")
Why This Works
By explicitly specifying bash.exe, you're replicating the exact environment where your script works (Git Bash). This ensures the script is executed properly, and the exit code you set in return_value.sh gets passed back to Python correctly.
Quick Troubleshooting Checks
If you still run into issues:
- Double-check that both
bash_executableandscript_pathare correct (use absolute paths if needed). - Test running
bash.exe ./return_value.shdirectly in Command Prompt—if it returns 9 there, the Python code should work too.
内容的提问来源于stack exchange,提问作者Mike Waring

