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

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 1
    This doesn't answer your question, but consider using [the Python bindings for libgit2](https://github.com/libgit2/pygit2) instead of `subprocess`. It should offer a nicer interface than having to build up strings as well as better performance and cross-platform support without needing `git` on the user's `$PATH`. – ChrisGPT was on strike Nov 24 '19 at 21:29
  • Possible duplicate of [Force "git status" to output color on the terminal (inside a script)](https://stackoverflow.com/questions/16073708/force-git-status-to-output-color-on-the-terminal-inside-a-script) – phd Nov 24 '19 at 22:10

1 Answers1

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.

Mats Wichmann
  • 800
  • 6
  • 6
  • `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. – Eugene Yarmash Nov 25 '19 at 12:35
  • Short of rewriting git... try this question to see if it helps: [1401002](https://stackoverflow.com/questions/1401002/how-to-trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe?noredirect=1) – Mats Wichmann Nov 25 '19 at 17:22
  • 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. – Eugene Yarmash Nov 25 '19 at 19:33