如何使用Python执行带管道的git log命令并解决subprocess报错
报错原因
- 第二次代码返回码128的报错:调用
subprocess.check_output时没有加shell=True参数,此时subprocess会将整条命令字符串拆分为参数直接传给git程序,管道符|被git识别为无效的版本/路径参数,因此抛出致命错误。 - 第一次代码报错:你使用了shell模式,但如果运行环境是Windows系统,系统自带的
sort命令不支持Unix系的-u(去重)参数,执行时参数识别失败抛出错误。
解决方案
推荐避免依赖shell管道,用Python原生能力做排序去重,跨平台兼容性最佳,写法如下:
import subprocess # 直接传参数列表不需要开启shell模式,安全性和兼容性更高 git_cmd = ['git', 'log', '--format=', '--name-only', '--since=2021-08-26'] try: stdout = subprocess.check_output(git_cmd, stderr=subprocess.STDOUT).decode('utf-8') # 分割结果、过滤空行、去重后排序,等价于原命令中 | sort -u 的效果 res = sorted(set(filter(None, stdout.splitlines()))) print('\n'.join(res)) except subprocess.CalledProcessError as e: print("Exception on process, rc", e.returncode, "stdout=", e.output.decode('utf-8', errors='ignore'))
如果坚持使用shell管道写法,仅需在check_output参数中添加shell=True即可,注意该写法仅适配Unix/Linux/macOS环境,Windows环境需额外安装GNU工具链替换系统原生sort命令:
import subprocess git_cmd = f'git log --format="" --name-only --since=2021-08-26 | sort -u' try: # 添加shell=True启用shell语法解析 stdout = subprocess.check_output(git_cmd, stderr=subprocess.STDOUT, shell=True).decode('utf-8') print(stdout) except subprocess.CalledProcessError as e: print("Exception on process, rc", e.returncode, "stdout=", e.output)
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

