How to preserve colors when capturing output from Git commands?

泪湿孤枕 提交于 2021-02-11 17:41:23

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/59022549/how-to-preserve-colors-when-capturing-output-from-git-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!