Python2 TypeError: must be unicode, not str for io module
I am using python netsnmp interface, in netsnmp, it is called C message and print error message, I want to write this message to string. So I found a blog: Redirecting all kinds of stdout in Python
But I have problems with Python 2.7.x, the code is for Python 3.x
this is a simple option:
#!/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')))
but run this code:
Traceback (most recent call last):
File "test2.py", line 40, in <module>
print('foobar')
TypeError: must be unicode, not str
I have a search for several hours and cannot explain the reason
+3
source to share
1 answer
Interestingly, I think the Python2 code is present in the comment in _redirect_stdout. But there is one more line that I think should also change. So change _redirect_stdout to:
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
+2
source to share