Skip to content
Advertisement

How to turn off printing result of python “sh” library

I’m working on services with Python, when I try to get status of a service with Python sh library, It will return results in a variable like so:

import sh
status = str(sh.service('nginx','status'))
if 'active' in status:
    print('ready')

It works fine, but when I try to get status of supervisor service it will print all the results in the terminal and destroys my command outputs.

So how to turn off this result which prints in terminal?

Advertisement

Answer

You’d need to redirect the output.

Either to /dev/null:

sh.service('nginx','status', _out='/dev/null')

or to a StringIO object for you to check the output:

from io import StringIO

buffer = StringIO()
sh.service('nginx','status', _out=buffer)
output = buffer.getvalue()

Use _err to redirect stderr output.

Advertisement