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

如何让Python subprocess获取PowerShell脚本的退出码?

问题解决:让Python脚本返回PowerShell脚本的错误码

你的问题在于原脚本没有正确传递PowerShell脚本的退出码,且shell=True会干扰退出码的获取。以下是两种可行的解决方法:

方法1:改进Popen调用

修改后的pssa.py代码:

import subprocess
import sys

# 调用PowerShell执行脚本,-File参数确保返回脚本自身的退出码
p = subprocess.Popen(
    ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", ".\\pre-commit.ps1"],
    stdout=sys.stdout,
    stderr=sys.stderr
)
# 等待进程执行完成,获取返回码
return_code = p.wait()
# 让Python脚本返回相同的错误码
sys.exit(return_code)

方法2:使用更简洁的subprocess.run()

subprocess.run()是Python 3.5+推荐的方式,它会自动等待进程完成:

import subprocess
import sys

# 执行PowerShell脚本,check=False表示不主动抛出异常
result = subprocess.run(
    ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", ".\\pre-commit.ps1"],
    stdout=sys.stdout,
    stderr=sys.stderr,
    check=False
)
# 传递PowerShell脚本的退出码给Python脚本的返回值
sys.exit(result.returncode)

关键说明

  1. 去掉shell=True:在Windows下,shell=True会通过cmd.exe启动命令,导致返回的是cmd.exe的退出码而非PowerShell的,干扰错误状态识别。
  2. 添加-File参数:PowerShell默认会将脚本内容当作命令块执行,-File参数会让它直接执行脚本文件,并返回脚本的退出码。
  3. -ExecutionPolicy Bypass:如果你的系统限制了PowerShell脚本执行权限,这个参数可以临时绕过执行策略,确保脚本能正常运行(根据实际情况可调整)。
  4. 主动返回退出码:通过sys.exit()将PowerShell的返回码传递出去,这样pre-commit run就能识别到脚本的失败状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:40:42