1

I want to repeat block of codes until successful output but want to display only successful messages.

while i < 6:
    try:
      sys.tracebacklimit = 0       #this line seems not work
      gluster_volume_names = []
      gstatus_output = subprocess.check_output('gstatus -a -o json ', shell=True).decode()
      date, time, json_part = gstatus_output.split(maxsplit=2)
      gluster_info = json.loads(json_part)
      volume_list = gluster_info["volume_summary"]
      ....
      ....
      break
    except:
      i += 1
      continue

But I don't know how to suppress these output below. (unsuccessful run) They are not the outcome I want. The block of code eventually ran successfully after less than 5 tries then exit.

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/EGG-INFO/scripts/gstatus", line 143, in main
  File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/gstatus/libgluster/cluster.py", line 543, in update_state
gstatus.libutils.excepts.GlusterFailedVolume: Unable to query volume 'BLAH'
Possible cause: cluster is currently reconverging after a nodehas entered a disconnected state.
Response: Rerun gstatus or issue a peer status command to confirm

Please help!

netthing
  • 47
  • 1
  • 8
  • this script is launched by another application with hard-coded line. I cannot use 2>/dev/null. sigh... But thanks for quick response @Cowboy_Patrick – netthing Nov 12 '20 at 06:09

3 Answers3

0

If you just want to suppress the errors in the console on a linux-system you can try:

python yourCode.py 2>/dev/null

With this you can also suppress stdout:

python yourCode.py 1>/dev/null

0

Instead of using subprocess.check_output, you should use the standard subprocess.run method and pipe the standard error to /dev/null. Use the following instead:

gstatus_output = subprocess.run('gstatus -a -o json ', shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode()

pip1726
  • 173
  • 1
  • 9
  • 1
    awesome! tested in my code with 'gstatus -a -o json && sleep 2' and run as expected. Thank you very much pip1726 – netthing Nov 13 '20 at 16:11
0

One possibility is to redirect standard output and standard error to a string. After execution, you can choose whether to print the results of the string, or discard it and try again.

from contextlib import redirect_stdout, redirect_stderr
import io

f = io.StringIO()
with redirect_stdout(f):
    with redirect_stderr(f):
        .... whatever you want ....
s = f.getvalue()
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22