Suppress stdout / stderr print from Python functions

前端 未结 9 1892
情歌与酒
情歌与酒 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:35

    My solution is similar to yours but uses contextlib and is a little shorter and easier to understand (IMHO).

    import contextlib
    
    
    @contextlib.contextmanager
    def stdchannel_redirected(stdchannel, dest_filename):
        """
        A context manager to temporarily redirect stdout or stderr
    
        e.g.:
    
    
        with stdchannel_redirected(sys.stderr, os.devnull):
            if compiler.has_function('clock_gettime', libraries=['rt']):
                libraries.append('rt')
        """
    
        try:
            oldstdchannel = os.dup(stdchannel.fileno())
            dest_file = open(dest_filename, 'w')
            os.dup2(dest_file.fileno(), stdchannel.fileno())
    
            yield
        finally:
            if oldstdchannel is not None:
                os.dup2(oldstdchannel, stdchannel.fileno())
            if dest_file is not None:
                dest_file.close()
    

    The context for why I created this is at this blog post. Similar to yours I think.

    I use it like this in a setup.py:

    with stdchannel_redirected(sys.stderr, os.devnull):
        if compiler.has_function('clock_gettime', libraries=['rt']):
            libraries.append('rt')
    

提交回复
热议问题