You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下Python subprocess返回Shell脚本错误退出码问题

Fixing Subprocess Exit Code Issue When Calling Sh Script on Windows 10

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_executable and script_path are correct (use absolute paths if needed).
  • Test running bash.exe ./return_value.sh directly in Command Prompt—if it returns 9 there, the Python code should work too.

内容的提问来源于stack exchange,提问作者Mike Waring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:12:12