user1601716
user1601716

Reputation: 1993

get subprocess to format correctly

I am trying to execute an ansible-playbook commend in subprocess at the end of a python script, which does 'magic' before kicking off the correct command.

If you are not familiar with ansible-playbook. The output is normally colorful(green/yellow/red text) and is correctly spaced.

I would be fine if python just kicked off a command and exited if need be.

What I am getting currently is black and white text after the command has completed.

I want to get the normal color outout in real time as if I ran ansible-playbook from the command line. Is there a way to do this?

my current code is as follows:

command = '{0} --flush-cache -f 20 -i {1}/dyn_inv.py --extra-vars @{2}/vars.json {3}'.format(ansible_playbook_loc, script_path, var_path, args.playbook[0])
print command
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
devices = process.communicate()[0].rstrip('\n').split()
print devices

Upvotes: 1

Views: 648

Answers (1)

larsks
larsks

Reputation: 311596

Ansible by default will only colorize text when its output is connected to a terminal. You can force it to use color codes by setting ANSIBLE_FORCE_COLOR=1 in the environment. For example:

import os
os.environ['ANSIBLE_FORCE_COLOR'] = '1'

You can accomplish the same thing by setting the force_color option in your ansible.cfg.

Upvotes: 4

Related Questions