1

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:

enter image description here

How to preserve colors in the captured output (both stdout and stderr)?

2

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

push doesn't take --color, that's the problem. I need some generic way to enable colors for all commands, whether the output goes to a terminal or not.
Short of rewriting git... try this question to see if it helps: 1401002
Yeah, using script or unbuffer is definitely an option. I was hoping there was an envariable enabling colors everywhere in Git, that would be ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.