How to turn off printing result of python "sh" library

231 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST 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.

0
On

Also it would be handled by (helps to avoid printing on terminal):

try:
    ...
except shErrorReturnCode:
    ...