【问题标题】:Why is redirection not working with python scripts? [duplicate]为什么重定向不适用于 python 脚本? [复制]
【发布时间】:2012-12-12 11:15:10
【问题描述】:

可能重复:
Setting the correct encoding when piping stdout in python

以下内容按预期在 python shell (2.7.3) 中运行

for i in range(999):
    print i, unichr(i)

将其保存在文件 (asd.py) 中,并在 shell 中运行

$ ./asd.py

也可以,但是

$ ./asd.py > asd.txt

给予:

Traceback (most recent call last):
  File "./asd.py", line 3, in <module>
    print i, unichr(i)
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)

这是为什么呢?如何解决?

【问题讨论】:

标签: python bash shell redirect


【解决方案1】:

试试这个代码,

#!/usr/bin/python
for i in range(999):
   print i, unichr(i).encode('utf-8')

【讨论】:

  • 嗯?有什么区别?
  • @glglgl 区别是 .encode('utf-8')
  • 它工作,但在 gedit 中打开文件,它说:你打开的文件有一些无效字符。如果您继续编辑此文件,您可能会损坏此文档。这是为什么呢?
  • "$ iconv -f utf-8 asd.txt" 试试这个命令
  • @Ammar 对不起,我是瞎子。没看到...
猜你喜欢
  • 2014-01-04
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2018-10-10
  • 2021-04-04
  • 1970-01-01
相关资源
最近更新 更多