【问题标题】:How to preserve colors when capturing output from Git commands?从 Git 命令捕获输出时如何保留颜色?
【发布时间】:2020-03-20 04:43:28
【问题描述】:

我有一个用 Python 实现的自定义 Git 命令,它使用来自 subprocess 模块的方法来调用 git。我注意到,根据使用的方法,输出可能会或可能不会被着色,例如:

import subprocess

subprocess.run('git push origin --delete foobar', shell=True)
print()
print(subprocess.run('git push origin --delete foobar', shell=True,
                     capture_output=True, encoding='utf-8').stderr, end='')

输出:

如何在捕获的输出(stdout 和 stderr)中保留颜色?

【问题讨论】:

标签: python git terminal subprocess


【解决方案1】:

许多命令会检测它们是否没有将输出发送到“终端”,如果没有,则不添加终端特定代码来显示颜色。当您缺少颜色时,就会出现这种情况。 一些 git 命令(不确定所有命令)可以采用--color 参数 - 请查看手册页。

【讨论】:

  • push 不接受--color,这就是问题所在。我需要一些通用的方法来为所有命令启用颜色,无论输出是否进入终端。
  • Short of rewriting git...试试这个问题看看是否有帮助:1401002
  • 是的,使用scriptunbuffer 绝对是一种选择。我希望在 Git 中到处都有一种可变的启用颜色,那将是理想的。
猜你喜欢
  • 2012-11-22
  • 2015-11-05
  • 2013-07-03
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2019-01-24
  • 2011-11-30
相关资源
最近更新 更多