简体   繁体   English

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

[英]Django management command raises UnicodeEncodeError only when redirecting output to file

I have built a Django management command that prints out some stuff on stdout (using print ). 我建立了一个Django管理命令 ,可以在stdout上打印出一些东西(使用print )。 All works fine, but... 一切正常,但是...

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 我尝试了./manage.py my_command | less ./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. ./manage.py my_command | less只是为了好玩,并表现出一定的产出,遇到的第一个非ASCII字符大概前行。 Output has some UTF-8 chars, no way around that. 输出包含一些UTF-8字符,无法解决。

Same error happens on Mac laptop and on Red Hat Linux server. 在Mac笔记本电脑和Red Hat Linux服务器上也会发生相同的错误。 Using Python 2.7.9 使用Python 2.7.9

What's happening here, and how can I dump the info to a file? 这是怎么回事,如何将信息转储到文件中?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM