Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colored output from fabric script

I'm trying to color my output from fabric script, so I do something like this:

local("hg pull")
print(blue(local("hg update")))
local("hg status")

I expected to have the 'hg update' response print in blue, but instead I get the result of the next line 'hg status' in blue.

In the Fabric documentation there are examples with coloring hard-coded strings, which work as I expect. Do you have any advice on how I can color response to just a single local command?

like image 223
Grzegorz Avatar asked Sep 05 '13 11:09

Grzegorz


2 Answers

This is what I use:

local("hg pull")
res = local("hg update", capture=True)
print(blue(res))
local("hg status")

[Edit] you also need the capture=True to fetch the output.

like image 196
RickyA Avatar answered Oct 15 '22 03:10

RickyA


Color functions in fabric are for simple strings, not for command output. But you can implement your own context manager for coloring:

from contextlib import contextmanager
BLUE = 34  # https://github.com/fabric/fabric/blob/1.7/fabric/colors.py#L40

@contextmanager
def colored_output(color):
    print("\033[%sm" % color, end="")
    yield
    print("\033[0m", end="")

with colored_output(BLUE):
    local("hg update")

Another way to achive your goal is to use local(..., capture=True), but you will not see any output until command is finished (help on local command).

like image 25
Allactaga Avatar answered Oct 15 '22 03:10

Allactaga