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

subprocess调用git命令报CalledProcessError exit status 128的解决办法

subprocess调用带管道的git命令返回128错误的解决方法

原始实现

最初通过subprocess执行内置sed管道的git命令获取GITID,代码如下:

GITID=sh( 'git describe --dirty --long --tags --abbrev=10 | sed -e "s:/:__:g"' ).strip()

完整业务逻辑代码:

try:
    # 校验文件可读,不可读则抛出异常
    f = open(self.path, "r")

    # 调用nyq处理yaml,退出码非0则抛出异常 => check=True
    # TODO : 待nyq纳入mcook遗留代码后改用对象调用
    proc = subprocess.Popen(["nyq", self.path, str('regressions.' + self.regressionName)],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8')
    stdout, stderr = proc.communicate()

    # TODO : 新增nyq执行退出码校验
    if proc.returncode != 0:
        logging.error(
            "执行nyq出错 ({})".format(proc.returncode))
        raise Exception(stdout)

    # 从nyq输出生成YAML对象,内容不是合法YAML流则抛出异常
    list_files = stdout
    self.parsed_data = yaml.load(list_files)  # 加载EMC数据
except Exception as exc:
    logging.error("嵌套YAML处理过程出错:")
    logging.error(exc)
    sys.exit(1)

错误表现

运行时抛出CalledProcessError,退出状态码为128。

错误原因

subprocess默认不启用shell解释器,带|管道符的命令传入后,会将管道符和后续的sed命令全部作为git的入参,导致git执行失败返回128错误码。

修复方案

去掉命令中的sed逻辑,改用Python原生的字符串replace方法处理git输出的内容,修正后的代码如下:

GITID=sh( 'git describe --dirty --long --tags --abbrev=10').replace('/', '__').strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:57:05