正如@JimDeville所说,您可以交换标准输出:
#!python2.7import ioimport sysdef foo(): print 'hello, world!'capture = io.BytesIO()save,sys.stdout = sys.stdout,capturefoo()sys.stdout = saveprint capture.getvalue()
输出:
hello, world!
io.StringIO由于
stdout预期是Unipre流,因此使用了Python 3版本:
#!python3import ioimport sysdef foo(): print('hello, world!')capture = io.StringIO()save,sys.stdout = sys.stdout,capturefoo()sys.stdout = saveprint(capture.getvalue())
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)