我使用netsnmp python接口,在netsnmp中,它调用了C扩展并打印错误消息,我想把这个消息捕捉到字符串中。所以我找到了一个博客:Redirecting all kinds of stdout in Python
但是我在使用python2.7.x时遇到了麻烦,代码是针对python3.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')))
但是运行这个代码得到:
^{pr2}$我找了几个小时,找不出原因
有趣的是,我认为Python2代码就在_redirect_stdout的注释中。但我认为还有一条线需要改变。因此,将重定向到:
相关问题 更多 >
编程相关推荐