Suppressing printout of “Exception … ignored” message in Python 3

前端 未结 3 700

There is a known issue in Python, where \"close failed in file object destructor\" when \"Broken pipe\" happens on stdout - Python tracker Issue 11380; also seen in python - Why

3条回答
  •  面向向阳花
    2021-02-19 09:18

    This is a VERY ugly hack to suppress the error message from being shown in case printing to stdout caused a broken pipe (e.g. because a pager process invoked like your-program.py | less was quit without scrolling to the bottom of the output:

    try:
        actual_code()
    except BrokenPipeError:
        sys.stdout = os.fdopen(1)
    

提交回复
热议问题