最近我寫了一個靜態頁面生成器。 我想用docker來部署我的項目。我使用python3。Docker,python3 yaml.safe_load()讀取中文文件無法正常工作
def load_posts_config(config):
metadata = {}
for c in os.listdir(config['articles']['config']):
cpath = os.path.join(config['articles']['config'], c)
cfh = open(cpath, 'r')
meta = yaml.safe_load(cfh)
cfh.close()
metadata[meta['post_id']] = meta
return metadata
在cfh
的配置文件,也有一些中國字。我在我自己的Ubuntu 16.04LTS,python3.5.2中運行我的腳本。然而,當我在泊塢窗跑了(其中Python版本3.5.3是),它輸出錯誤:
[email protected]:/build/blog# python3 bumblebee.py
Traceback (most recent call last):
File "bumblebee.py", line 80, in <module>
article_infos = load_posts_config(config)
File "bumblebee.py", line 56, in load_posts_config
meta = yaml.safe_load(cfh)
File "/usr/local/lib/python3.5/dist-packages/yaml/__init__.py", line 70, in load
loader = Loader(stream)
File "/usr/local/lib/python3.5/dist-packages/yaml/loader.py", line 34, in __init__
Reader.__init__(self, stream)
File "/usr/local/lib/python3.5/dist-packages/yaml/reader.py", line 85, in __init__
self.determine_encoding()
File "/usr/local/lib/python3.5/dist-packages/yaml/reader.py", line 124, in determine_encoding
self.update_raw()
File "/usr/local/lib/python3.5/dist-packages/yaml/reader.py", line 178, in update_raw
data = self.stream.read(size)
File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 16: ordinal not in range(128)
這是很奇怪的。我認爲python3可以處理所有的unicode,我可以在我的本地計算機上運行它。 唯一的區別是python版本和環境,Ubuntu16.04lts工程中的python3.5.2和docker中的python3.5.3沒有。
有沒有人知道這個問題? 或者如何在我的Ubuntu 16.04 LTS中將python3.5.2更新到python3.5.3? 或某個地方的求職者尋求幫助?
Thx提前。
(PS:我已經試過yaml.load()
但失敗了)
試試這個,看看它是否指定
ENV LANG C.UTF-8
'進口IO; cfh = io.open(cpath,'r',encoding =「utf-8」);' –