因为print是输出到sys.out里面, 所以要替换标准的输出:
#coding: utf-8
class TextArea(object):
def __init__(self):
self.buffer = []
def write(self, *args, **kwargs):
self.buffer.append(args)
import sys
stdout = sys.stdout
sys.stdout = TextArea()
# print to TextArea
print("testA")
print("testB")
print("testC")
text_area, sys.stdout = sys.stdout, stdout
# print to console
print(text_area.buffer)
输出内容:
[('testA',), ('\n',), ('testB',), ('\n',), ('testC',), ('\n',)]
如果是json数据,可以增加一步处理:
data_get_json_ori = text_area.buffer[0] # json
data_get_json = json.loads(data_get_json_ori)
data_get= {}
host = ''
for key, value in data_get_json.items():
data_get[key] = value