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

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

    There is contextlib.redirect_stdout() function in Python 3.4:

    import io
    from contextlib import redirect_stdout
    
    with io.StringIO() as buf, redirect_stdout(buf):
        print('redirected')
        output = buf.getvalue()
    

    Here's code example that shows how to implement it on older Python versions.

提交回复
热议问题