MrDuk
MrDuk

Reputation: 18322

Can you have subprocesss.Popen retain color in stdout/stderr?

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?

Upvotes: 6

Views: 3589

Answers (2)

Ahmed
Ahmed

Reputation: 3012

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.

Upvotes: -1

Roland Smith
Roland Smith

Reputation: 43533

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.

Upvotes: 5

Related Questions