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

前端 未结 9 1659
野趣味
野趣味 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:43

    In Python3.6, the StringIO and cStringIO modules are gone, you should use io.StringIO instead.So you should do this like the first answer:

    import sys
    from io import StringIO
    
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    my_stdout = sys.stdout = StringIO()
    my_stderr = sys.stderr = StringIO()
    
    # blah blah lots of code ...
    
    sys.stdout = self.old_stdout
    sys.stderr = self.old_stderr
    
    // if you want to see the value of redirect output, be sure the std output is turn back
    print(my_stdout.getvalue())
    print(my_stderr.getvalue())
    
    my_stdout.close()
    my_stderr.close()
    

提交回复
热议问题