但是我遇到了Python 2.7.x的问题,代码是Python 3.x
这是一个简单的版本:
#!/usr/bin/env python
# -*- coding: utf-8
from __future__ import unicode_literals
from contextlib import contextmanager
import io
import sys
import os
import tempfile
@contextmanager
def stdout_redirector(stream):
original_stdout_fd = sys.stdout.fileno()
def _redirect_stdout(to_fd):
sys.stdout.close()
os.dup2(to_fd, original_stdout_fd)
#_buf = os.fdopen(original_stdout_fd, 'wb')
_buf = io.open(original_stdout_fd, 'wb') # for BufferWritter object, not file object
sys.stdout = io.TextIOWrapper(_buf)
saved_stdout_fd = os.dup(original_stdout_fd)
try:
tfile = tempfile.TemporaryFile(mode='w+b')
_redirect_stdout(tfile.fileno())
yield
_redirect_stdout(saved_stdout_fd)
tfile.flush()
tfile.seek(0, io.SEEK_SET)
stream.write(tfile.read())
finally:
tfile.close()
os.close(saved_stdout_fd)
f = io.BytesIO()
with stdout_redirector(f):
print('foobar')
print(12)
print('Got stdout: "{0}"'.format(f.getvalue().decode('utf-8')))
但运行此代码获取:
Traceback (most recent call last):
File "test2.py", line 40, in <module>
print('foobar')
TypeError: must be unicode, not str
我有几个小时的搜索,无法说明原因
答案 0 :(得分:2)
有趣的是,我认为Python2代码存在于_redirect_stdout的注释中。但我认为还有另一条线需要改变。因此,将 _redirect_stdout 更改为:
def _redirect_stdout(to_fd):
sys.stdout.close()
os.dup2(to_fd, original_stdout_fd)
_buf = os.fdopen(original_stdout_fd, 'wb')
#_buf = io.open(original_stdout_fd, 'wb') # for BufferWritter object, not file object
sys.stdout = _buf