python - 将 stdout 重定向到具有 unicode 编码的文件,同时在 python 2 中保留 windows eol

标签 python python-2.7 unicode io eol

我在这里碰壁了。我需要将所有输出重定向到一个文件,但我需要将此文件编码为 utf-8。问题是使用 codecs.open 时:

# errLog = io.open(os.path.join(os.getcwdu(),u'BashBugDump.log'), 'w',
#                  encoding='utf-8')
errLog = codecs.open(os.path.join(os.getcwdu(), u'BashBugDump.log'),
                     'w', encoding='utf-8')
sys.stdout = errLog
sys.stderr = errLog

codecs 以二进制模式打开文件,导致 \n 行终止符。我尝试使用 io.open 但这并不适用于整个代码库中使用的 print 语句(请参阅 Python 2.7: print doesn't speak unicode to the io module?python: TypeError: can't write str to text stream )

我不是唯一遇到此问题的人,例如请参阅 here但是solution they adopted特定于我们不使用的日志记录模块。

另请参阅这不会修复 python 中的错误:https://bugs.python.org/issue2131

那么在 python2 中执行此操作的正确方法是什么?

最佳答案

选项1

重定向是一个shell操作。您根本不必更改 Python 代码,但您必须告诉 Python 如果重定向要使用什么编码。这是通过环境变量完成的。以下代码将 stdout 和 stderr 重定向到一个 UTF-8 编码的文件:

测试.bat

set PYTHONIOENCODING=utf8
python test.py >out.txt 2>&1

测试.py

#coding:utf8
import sys
print u"我不喜欢你女朋友!"
print >>sys.stderr, u"你需要一个新的。"

out.txt(以UTF-8编码)

我不喜欢你女朋友!
你需要一个新的。

out.txt 的十六进制转储

0000: E6 88 91 E4 B8 8D E5 96 9C E6 AC A2 E4 BD A0 E5
0010: A5 B3 E6 9C 8B E5 8F 8B EF BC 81 0D 0A E4 BD A0 
0020: E9 9C 80 E8 A6 81 E4 B8 80 E4 B8 AA E6 96 B0 E7
0030: 9A 84 E3 80 82 0D 0A

注意:您确实需要打印 Unicode 字符串才能工作。打印字节字符串,您将获得打印的字节。

选项 2

codecs.open 可能会强制二进制模式,但 codecs.getwriter 不会。给它一个以文本模式打开的文件:

#coding:utf8
import sys
import codecs
sys.stdout = sys.stderr = codecs.getwriter('utf8')(open('out.txt','w'))
print u"我不喜欢你女朋友!"
print >>sys.stderr, u"你需要一个新的。"

(与上面相同的输出和 hexdump)

关于python - 将 stdout 重定向到具有 unicode 编码的文件,同时在 python 2 中保留 windows eol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40969478/

相关文章:

python - python mplot3D 中的 2D 图与 3D 轴壁不齐平

python - 如何在 Tkinter GUI 中附加删除功能

python - 在 Heroku 上使用 Python2.7 导入 sqlite3

python - 使用python中的beautifulsoup从具有更多文本内容的网页中提取数据

python - 我的 python 脚本有什么问题?不打印变量

python - Pyramid pserve.exe语法错误

algorithm - 需要一种更快、更有效的方法来将元素添加到 python 中的列表中

c# - Unicode 字符串到二进制字符串和二进制字符串到 unicode c#

python - numpy loadtxt、unicode 和 python 2 或 3

unicode - Unicode 联盟是否打算让 UTF-16 用完字符?