Suppress stdout / stderr print from Python functions

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

    Not really requested by the OP, but I needed to hide and store the output, and did like follows:

    from io import StringIO
    import sys
    
    class Hider:
        def __init__(self, channels=('stdout',)):
            self._stomach = StringIO()
            self._orig = {ch : None for ch in channels}
    
        def __enter__(self):
            for ch in self._orig:
                self._orig[ch] = getattr(sys, ch)
                setattr(sys, ch, self)
            return self
    
        def write(self, string):
            self._stomach.write(string)
    
        def flush(self):
            pass
    
        def autopsy(self):
            return self._stomach.getvalue()
    
        def __exit__(self, *args):
            for ch in self._orig:
                setattr(sys, ch, self._orig[ch])
    

    Usage:

    with Hider() as h:
        spammy_function()
        result = h.autopsy()
    

    (tested only with Python 3)

    EDIT: now allows to select stderr, stdout or both, as in Hider([stdout, stderr])

提交回复
热议问题