问题
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