Skip to main content
 首页 » 编程设计

python之传递给其他命令时编码发生变化

2025年05月04日13haluo1

我有一个文件,我从 test 读取了它。这个文件是UTF-8。在我的简单示例中,它仅包含丹麦语字母“Ø”。

然后我有一个 Python 脚本,它读取这个文件,在这个例子中,只打印每一行。

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
import codecs 
import sys 
 
filename = sys.argv[1] 
 
f = codecs.open(filename, 'r', 'utf-8') 
 
for lines in f: 
  print lines 

调用此 parse.py。现在,当我在终端中运行 ./parse.py test 时,我得到以下输出:

Ø 

改为调用 ./parse.py test | less 给我:

Traceback (most recent call last): 
  File "./test.py", line 12, in <module> 
    print lines 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd8' in position 11: ordinal not in range(128) 

我确定我的测试文件是“UTF-8”:

$ file -I test 
test: text/plain; charset=utf-8 

以及我的 $LC_TYPE 是 'UTF-8'

我做错了什么?我如何让它工作,以便我可以将 parse.py 的输出传递给下一个命令?

请您参考如下方法:

这可能是 less 的问题,请参阅 this article一些提示。也许更改 less 的配置会有所帮助。

If your system supports the UTF-8 encoding of Unicode for non-ASCII text, as many modern systems do, you should either set your locale to something that includes the string "UTF-8" or "UTF8" (either uppercase or lowercase is ok), or set LESSCHARSET to "utf-8".

好的,这不是问题所在...所以根据评论更新答案。 需要在打印前对字符串进行编码。 This article给出原因,总结:需要告诉python如何对unicode进行编码。