问题
工作的时候遇到问题,需要调用他人的函数并获取该输出,但是该函数的输出是输出到sys.stdout标准输出里面的,所以要进行从定向,下为我解决该问题的方案和过程。
解决过程
一开始想到的解决方案就是重定向,讲标准输出重定向到一个对应的变量缓存中,执行完调用后,即可获取。
单纯的重定向需要只需要实现write接口即可,但是由于我调用的库还使用了创建子进程进行。所以当我使用该对象时,遇到了对应的保错,需要继续实现fileno借口,fileno接口返回一个由os,open创建的文件描述符。具体的代码如下:
#重定向代码
import os
import sys
class GetOutPut(object):
def __init__(self):
self.__tmp_file_path = "/tmp/getoutput.tmpfile"
self.__fileno = os.open(self.__tmp_file_path, os.O_RDWR | os.O_CREAT)
def write(self, s):
os.write(self.__fileno, s.encode())
def get_info(self):
'''
在读取字符串时,不要在循环中直接decode要将所有字符读取出来后,再进
行decode,防止unicode字符被阶段,引发解码错误
'''
buf = b""
result = b""
buf_size = 1024
os.lseek(self.__fileno, 0, os.SEEK_SET)
buf = os.read(self.__fileno, buf_size)
while buf != b"":
result += buf
os.read(self.__fileno, buf_size)
return result.decode()
def clear(self):
os.close(self.__fileno)
os.unlink(self.__tmp_file_path)
# 如果需要获取sys.stderr的输出还需覆盖实现flush
def flush(self):
pass