管道Python程序的输出时,Python解释器会对编码感到困惑,并将其设置为None.这意味着这样的程序:
# -*- coding: utf-8 -*-
print u"åäö"
Run Code Online (Sandbox Code Playgroud)
正常运行时会正常工作,但失败时:
UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ xa0'进行编码:序数不在范围内(128)
当在管道序列中使用时.
在配管时使这项工作的最佳方法是什么?我可以告诉它使用shell/filesystem /无论使用什么编码吗?
到目前为止我看到的建议是直接修改你的site.py,或者使用这个hack对defaultencoding进行硬编码:
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法使管道工作?
我有这个Python3代码尝试从utf-8编码文件中读取和打印:
f = open('mybook.txt', encoding='utf-8')
for line in f:
print(line)
Run Code Online (Sandbox Code Playgroud)
当我使用Sublime Text 3构建时,我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 18: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
但是,当我用python3在终端中执行我的代码时,它工作文件.
我的构建配置是
{
"cmd": ["/usr/local/bin/python3", "$file"]
, "selector": "source.python"
, "file_regex": "file \"(...*?)\", line ([0-9]+)"
}
Run Code Online (Sandbox Code Playgroud)
如果我将其更改为:
f = open('mybook.txt', encoding='utf-8')
for line in f:
print(line.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
然后它会打印utf-8编码的字节串(我认为这是正在发生的事情).
b'Hello\n'
b'\xc2\xab\xe2\x80\xa2\n'
b'Goodbye'
Run Code Online (Sandbox Code Playgroud)
但我也不知道如何从这个到打印屏幕上的unicode字符......
另外,如果我按照一个python程序尝试更改这个env变量,则无法在sublime文本3中执行,但是在bash中成功它仍然无法修复它.
我想在优胜美地的Sublime Text 3中将首选编码从US-ASCII更改为UTF-8。bash中的首选编码设置为UTF-8,因此当在终端中运行python时:
import locale
print(locale.getpreferredencoding())
Run Code Online (Sandbox Code Playgroud)
输出为:UTF-8
在Sublime Text中运行相同的代码时,输出为US-ASCII。
在Python的构建系统中设置3:
"encoding": "UTF-8"
Run Code Online (Sandbox Code Playgroud)
要么
"env": {"PYTHONIOENCODING": "utf-8}
Run Code Online (Sandbox Code Playgroud)
没有帮助。
如何永久更改设置,这样就不必调用locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')脚本来解决问题了。
encoding ×2
python ×2
python-3.x ×2
sublimetext3 ×2
utf-8 ×2
osx-yosemite ×1
python-2.x ×1
stdout ×1
sublimetext ×1
terminal ×1