从 Git 命令捕获输出时如何保留颜色? [英] How to preserve colors when capturing output from Git commands?
问题描述
我有一个用 Python 实现的自定义 Git 命令,它使用来自
如何在捕获的输出(标准输出和标准错误)中保留颜色?
许多命令会检测它们是否没有将输出发送到终端",如果没有,则不会添加特定于终端的代码来显示颜色.当您缺少颜色时就是这种情况.某些 git 命令,不确定所有命令,可以采用 --color
参数 - 检查联机帮助页.
I have a custom Git command implemented in Python that uses methods from the subprocess
module to call git
. I've noted that, depending on the method used, the output may or may not be colored, e.g.:
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='')
Output:
How to preserve colors in the captured output (both stdout and stderr)?
Many commands detect if they're not sending their output to a "terminal" and don't add the terminal-specific codes to display colors if not. That will be the case when you're missing the colors. Some git commands, not sure all of them, can take a --color
argument - check the manpages.
这篇关于从 Git 命令捕获输出时如何保留颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!