Search code examples
pythonsubprocesscolorama

subprocess.call output in color


Is there a way to display subprocess.call output in a different color and than come back to the default one? I am using colorama. but the below won't work for me. the print one works fine and prints test in green.

subprocess.call(["%s; " % Fore.GREEN, "hostname;" "%s" % Fore.RESET], shell=True)
subprocess.call([Fore.RED,'hostname'], shell=True)
print (Fore.GREEN,'test')

I have tried the above but it didn't work,

thanks for your help


Solution

  • You could use subprocess.run instead of subprocess.call.

    subproces.run has a capture_output keyword that can be used to achieve your goal, example:

    >>> import colorama
    >>> import subprocess
    >>> colorama.init(autoreset=True)
    >>> out =subprocess.run(['hostname'], capture_output=True)
    >>> print(colorama.Fore.GREEN + out.stdout.decode())
    darknet
    

    In this case, darknet is the hostname and it'll presumably be printed in green. I have also set the autoreset=True.

    Update

    $ docker container run --rm -it python:3.6-alpine sh
    / # pip install colorama
    Collecting colorama
      Downloading https://files.pythonhosted.org/packages/4f/a6/728666f39bfff1719fc94c481890b2106837da9318031f71a8424b662e12/colorama-0.4.1-py2.py3-none-any.whl
    Installing collected packages: colorama
    Successfully installed colorama-0.4.1
    / # python
    Python 3.6.9 (default, Aug 21 2019, 00:27:28) 
    [GCC 8.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import colorama
    >>> import subprocess
    >>> colorama.init(autoreset=True)
    >>> out = subprocess.run(['hostname'], capture_output=True)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python3.6/subprocess.py", line 423, in run
        with Popen(*popenargs, **kwargs) as process:
    TypeError: __init__() got an unexpected keyword argument 'capture_output'
    >>> process = subprocess.run(['hostname'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    >>> print(colorama.Fore.RED + process.stdout.decode())
    49e3284539b8
    

    From the docs https://docs.python.org/3/library/subprocess.html#subprocess.run, the same behavior of capture_output can be achieved using stdout=subprocess.PIPE, stderr=subprocess.PIPE as shown above.