Suppress stdout / stderr print from Python functions

前端 未结 9 1913
情歌与酒
情歌与酒 2020-11-29 06:59

I have a Python script that is using some closed-box Python functions (i.e. I can\'t edit these functions) provided by my employer. When I call these functions, they are pri

9条回答
  •  余生分开走
    2020-11-29 07:36

    I use a decorator for this. It saves sys.stdout and sys.stderr references and makes these variables point to null. Then, after the function execution the original references are retrieved. It is important to note the try/except block, that allows the retrieval of the original references even when an exception is raised on the function.

    def suppress_std(func):
        def wrapper(*args, **kwargs):
            stderr_tmp = sys.stderr
            stdout_tmp = sys.stdout
            null = open(os.devnull, 'w')
            sys.stdout = null
            sys.stderr = null
            try:
                result = func(*args, **kwargs)
                sys.stderr = stderr_tmp
                sys.stdout = stdout_tmp
                return result
            except:
                sys.stderr = stderr_tmp
                sys.stdout = stdout_tmp
                raise
        return wrapper
    

    To use:

    @suppress_std
    def function_std_suppressed():
        # code here
    

提交回复
热议问题