尝试将命令行输出保存到文件时出错
问题内容:
我正在运行python工具,并尝试将其输出保存到文件中。如果我不将输出保存到文件中,则该工具运行得很好。但是,当我尝试将输出保存到文件时,它会引发以下错误并中断程序:
File "./androdiff.py", line 118, in <module>
main(options, arguments)
File "./androdiff.py", line 94, in main
ddm.show()
File "./elsim/elsim/elsim_dalvik.py", line 772, in show
self.eld.show()
File "./elsim/elsim/elsim.py", line 435, in show
i.show()
File "./elsim/elsim/elsim_dalvik.py", line 688, in show
print hex(self.bb.bb.start + self.offset), self.pos_instruction, self.ins.get_name(), self.ins.show_buff( self.bb.bb.start + self.offset )
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0111' in position 35: ordinal not in range(128)
我试过command |less
,command > output
并且command | tee output
,所有的人都会抛出这样的错误。
请帮助解决问题。
谢谢!
问题答案:
在打印之前,您需要指定字符串的编码:
print unicode(hex(self.bb.bb.start + self.offset)).encode('utf-8')
print unicode(self.pos_instruction, self.ins.get_name()).encode('utf-8')
print unicode(self.ins.show_buff( self.bb.bb.start + self.offset )).encode('utf-8')
之所以可行,是因为在打印到终端时(它检测到终端使用utf-8),python会自动正确编码您的字符串(在您的情况下为utf-8)。
当您将输出重定向到文件时,Python没有有关应使用哪种编码的信息,它默认为ascii(这将导致您的错误)。
作为一般经验法则,请确保在打印之前始终对字符串进行编码,以使其print
在所有环境中都能正常工作。
最好的方法可能是为此定义自己的打印方法:
def myprint(unicodestr):
print unicodestr.encode('utf-8')
如果要避免上述情况,并使用默认的utf-8编码进行打印,则可以执行
import sys
import codecs
sys.stdout=codecs.getwriter('utf-8')(sys.stdout)
当心这种方法!某些第三方库可能取决于默认编码为ascii和break。请注意,整个混乱已在Python 3中得到解决(默认为UTF-8编码)