1. 设置标准输出的编码方式:
use getwriter() to get a stream encoder class for a specific encoding. Instantiate the class, passing sys.stdout as the only argument.
import codecs
import sys
text = u'pi: π'
# Wrap sys.stdout with a writer that knows how to handle encoding
# Unicode data.
wrapped_stdout = codecs.getwriter('UTF-8')(sys.stdout)
wrapped_stdout.write(u'Via write: ' + text + '\n')
# Replace sys.stdout with a writer
sys.stdout = wrapped_stdout
print u'Via print:', text
另外,如果要对项目的log系统进行修改,可以用
sys.stdout = MultiStream(wrapped_stdout)
MultStream 是一个类似文件的类, 往 python logger里写信息
class MultiStream:
"""
A file like class that writes to python logger
"""
def __init__(self, stdout):
self.stdout = stdout
self.fileno = stdout.fileno
self.consoleLog = False
def close(self):
pass
def flush(self):
if self.consoleLog:
self.stdout.flush()
def write(self, msg):
fileHandler = open(stdoutFileName, 'a')
try:
if fileHandler:
fileHandler.write(msg.encode('utf-8'))
except:
print traceback.format_exc()
if fileHandler:
fileHandler.write(msg)
if fileHandler:
fileHandler.close()
try:
if self.consoleLog:
print >> self.stdout, msg,
except:
print traceback.format_exc()