如何抑制stdout和stderr直到在python中成功?

时间:2020-11-12 05:58:57

标签: python python-3.x

我要重复代码块直到成功输出,但只想显示成功消息。

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

但是我不知道如何抑制下面的这些输出。 (运行失败)它们不是我想要的结果。少于5次尝试后,代码块最终成功运行,然后退出。

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

请帮助!

3 个答案:

答案 0 :(得分:0)

如果您只是想抑制Linux系统上控制台中的错误,可以尝试:

python yourCode.py 2>/dev/null

与此同时,您也可以禁止stdout:

python yourCode.py 1>/dev/null

答案 1 :(得分:0)

应该使用标准的subprocess.check_output方法而不是使用subprocess.run并将标准错误传递给/ dev / null。请改用以下内容:

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

答案 2 :(得分:0)

一种可能性是将标准输出和标准错误重定向到字符串。执行后,您可以选择是打印字符串的结果,还是将其丢弃并重试。

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()