6

I have the following code:

p = subprocess.Popen(cmd.split(' '), env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
      log.info(p.stdout.readline())
      if(p.poll() is not None):
        break

Which works ok, except for the fact that it removes all color issued. Is there a way to retain this?

MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • 1
    Which commands are you running? Note that programs like, say, `grep` check which type of output file they are using and will not output color codes if it doesn't look like a terminal. If you want to force it to always send the color codes you have to use the option `--color=always`. Other programs do the same – Bakuriu Jun 28 '16 at 19:37
  • Ah sure, makes sense - the command I'm trying in this example is `ansible` based commands. Ran outside of the script, beautiful rainbows of colors. In the script, not as pretty. – MrDuk Jun 28 '16 at 19:38
  • https://stackoverflow.com/q/56835373/94148 – aleung May 11 '20 at 07:52
  • colored output can be tricky... some programs (such as `git`) disable colors by default when they're part of `Popen('foo')`. If I'm having problems with colored output, almost invariably, the fault lies with the thing I'm calling from `Popen()`. Try forcing colors with CLI options (if `foo` it has them). – Mike Pennington Oct 30 '20 at 03:35

2 Answers2

5

You do not specify whan cmd is, but some programs do not emit the escape sequences necessary for color output on a terminal when they determine that their standard output is not actually connected to a terminal.

Depending on the program you may or may not be able to override that.

With ansible, you can set the force_color configuration variable to 1 to force color output.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • Beautiful! While you're here, any idea how I can get my output to stop printing extra `\n` on every line? (I can't accept your answer for another few minutes, sorry!) – MrDuk Jun 28 '16 at 19:45
-1

Add the following at the top of your Python script.

import os
os.environ['ANSIBLE_FORCE_COLOR'] = "TRUE"

Now if you run Ansible from Python by using subprocess.Popen, it will print the colors.

Ahmed
  • 2,825
  • 1
  • 25
  • 39