尝试将命令行输出保存到文件时出错 [英] Errors when trying to save command line output to a file

查看:235
本文介绍了尝试将命令行输出保存到文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个python工具,并尝试将其输出保存到一个文件。如果我不保存输出到一个文件,该工具运行完美。但是当我尝试将输出保存到文件时,它会抛出以下错误并中断程序:

I was running a python tool and trying to save its output to a file. If I don't save the output to a file, the tool runs perfectly fine. But when I try to save the output to the file, it throws following error and interrupt the program:

  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>输出命令|

I've tried command |less , command > output and command | tee output, all of them will throw such error.

请帮助解决这个问题。

谢谢!

推荐答案

您需要在打印之前指定字符串的编码:

You will want to specify the encoding of your string before you print it:

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')

这是因为python会自动

The reason this works is because python automatically encodes your string correctly (in your case utf-8) when printing to the terminal (it detects that the terminal uses utf-8).

当您将输出重定向到终端时,字符串正确地输出到终端(在您的情况下是utf-8)文件改为,Python没有关于应该使用什么编码的信息,它默认为ascii(这导致您的错误)。

When you are redirecting your output to a file instead, Python has no information about what encoding it should use and it defaults to ascii instead (which is causing your error).

作为一般的经验法则确保您始终在打印之前对字符串进行编码,以使打印在所有环境中都可正常工作。

As a general rule of thumb, make sure you always encode your string before printing to make print work in all environments.

最好的方法是定义您自己的打印方法:

The best method may be to define your own print method for this:

def myprint(unicodestr): 
    print unicodestr.encode('utf-8')

如果您想避免上述操作并使用utf-8编码进行打印可以做

If you want to avoid the above and make printing with utf-8 encoding the default you can do

import sys
import codecs
sys.stdout=codecs.getwriter('utf-8')(sys.stdout)

注意这种方法!一些第三方库可能依赖于ascii和break的默认编码。注意,这整个混乱已经解决在Python 3(默认为UTF-8编码)

Beware of this approach! Some third-party libraries may depend on the default encoding being ascii and break. Note that this whole mess has been resolved in Python 3 (which defaults to UTF-8 encoding)

这篇关于尝试将命令行输出保存到文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆