只有在将输出重定向到文件时,Django管理命令才会引发UnicodeEncodeError

时间:2021-04-14 00:03:43

I have built a Django management command that prints out some stuff on stdout (using print). All works fine, but...

我已经构建了一个Django管理命令,可以在stdout上打印出一些内容(使用print)。一切正常,但......

When I try to redirect the output to a file, using

当我尝试将输出重定向到文件时,使用

./manage.py my_command > a_file.txt

I get:

我明白了:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 14: ordinal not in range(128)

No traceback, just that.

没有追溯,就是这样。

I tried ./manage.py my_command | less just for the fun of it, and it showed some output, presumably lines before first non-ASCII char was encountered. Output has some UTF-8 chars, no way around that.

我试过./manage.py my_command |不仅仅是为了它的乐趣,它显示了一些输出,可能是在遇到第一个非ASCII字符之前的行。输出有一些UTF-8字符,没办法。

Same error happens on Mac laptop and on Red Hat Linux server. Using Python 2.7.9

在Mac笔记本电脑和Red Hat Linux服务器上发生同样的错误。使用Python 2.7.9

What's happening here, and how can I dump the info to a file?

这里发生了什么,以及如何将信息转储到文件中?

1 个解决方案

#1


1  

You can change the standard output of the script with UTF-8 encoded output :

您可以使用UTF-8编码输出更改脚本的标准输出:

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

Or you can encode your strings before printing them:

或者您可以在打印之前对字符串进行编码:

print string_containing_unicode.encode('utf-8')

#1


1  

You can change the standard output of the script with UTF-8 encoded output :

您可以使用UTF-8编码输出更改脚本的标准输出:

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

Or you can encode your strings before printing them:

或者您可以在打印之前对字符串进行编码:

print string_containing_unicode.encode('utf-8')