Can I redirect the stdout in python into some sort of string buffer?

前端 未结 9 1565
野趣味
野趣味 2020-11-22 06:23

I\'m using python\'s ftplib to write a small FTP client, but some of the functions in the package don\'t return string output, but print to stdout.

9条回答
  •  难免孤独
    2020-11-22 06:36

    A context manager for python3:

    import sys
    from io import StringIO
    
    
    class RedirectedStdout:
        def __init__(self):
            self._stdout = None
            self._string_io = None
    
        def __enter__(self):
            self._stdout = sys.stdout
            sys.stdout = self._string_io = StringIO()
            return self
    
        def __exit__(self, type, value, traceback):
            sys.stdout = self._stdout
    
        def __str__(self):
            return self._string_io.getvalue()
    

    use like this:

    >>> with RedirectedStdout() as out:
    >>>     print('asdf')
    >>>     s = str(out)
    >>>     print('bsdf')
    >>> print(s, out)
    'asdf\n' 'asdf\nbsdf\n'
    

提交回复
热议问题