python - 尝试将命令行输出保存到文件时出错

标签 python linux unicode command-line pipe

我正在运行一个 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 > outputcommand | tee 输出,都会抛出这样的错误。

请帮助解决问题。

谢谢!

最佳答案

如果无法自动确定 stdout 字符编码,则显式设置 PYTHONIOENCODING 环境变量,例如,当输出重定向到文件时:

$ PYTHONIOENCODING=utf-8 python app.py > file

如果输出可能会到达终端,请不要在脚本中对字符编码进行硬编码;而是打印 Unicode 字符串,让用户配置他们的环境。

关于python - 尝试将命令行输出保存到文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24297838/

相关文章:

linux - encfs解密,文件名编码 'nameio/block' 4.0.0不支持

MySQL 字符集转换

python - 如何使用python将其中包含unicode的字符串转换为unicode

php - 这种格式的日本日期

Python 3 使用 kwargs 替换嵌套字典值

python - 使用卷积自动编码器从 2D 到 3D

python - 与 PostgreSQL 数据库的 SQLAlchemy/psycopg2 连接是否加密

c - 你如何在类 linux 系统中创建、编译和使用静态和动态库?

linux - 在 SGE 作业中使用集群上的 tee 对 SIGTERM 进行故障排除

python - 通过使用不准确/不完整的字符串进行搜索来查找字典中的值