python2 TypeError:必须是unicode,而不是io模块的str
我使用netsnmppython接口,在netsnmp中,它称为C扩展名并打印错误消息,我想将此消息捕获为字符串。于是我找到了一个博客: 但是我在使用Python2.7.x时遇到了麻烦,代码是为Python3.x编写的 这是一个简单的例子:python2 TypeError:必须是unicode,而不是io模块的str,python,python-2.7,unicode,Python,Python 2.7,Unicode,我使用netsnmppython接口,在netsnmp中,它称为C扩展名并打印错误消息,我想将此消息捕获为字符串。于是我找到了一个博客: 但是我在使用Python2.7.x时遇到了麻烦,代码是为Python3.x编写的 这是一个简单的例子: #!/usr/bin/env python # -*- coding: utf-8 from __future__ import unicode_literals from contextlib import contextmanager import i
#!/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
回溯(最近一次呼叫最后一次):
文件“test2.py”,第40行,在
打印('foobar')
TypeError:必须是unicode,而不是str
我已经搜索了好几个小时,但找不到原因。有趣的是,我认为Python2代码在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