python2 TypeError:必须是unicode,而不是io模块的str

时间:2015-06-29 10:27:52

标签: python python-2.7 unicode

我使用netsnmp python接口,在netsnmp中,它调用C扩展并打印错误信息,我想将此消息捕获到字符串中。所以我找到了一个博客:Redirecting all kinds of stdout in Python

但是我遇到了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

我有几个小时的搜索,无法说明原因

1 个答案:

答案 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