Python,Docker-'ascii'编解码器无法编码字符

mac*_*azo 2 python csv python-3.x docker

我编写了一个python3脚本,该脚本进行了一些Web抓取并将一些信息存储在CSV文件中。该脚本可以在我的计算机上正常运行。当我尝试在Docker容器上运行脚本时会发生问题。该错误似乎在我的代码的这一部分上(出于本问题的目的而进一步简化)。

# default CSV module
import csv

# this is how an ACTUAL row looks like in my program, included it in case it was important
row = {'title': 'Electrochemical sensor for the determination of dopamine in presence of high concentration of ascorbic acid using a Fullerene-C60 coated gold electrode', 'url': 'https://onlinelibrary.wiley.com/doi/abs/10.1002/elan.200704073', 'author': 'Goyal, Rajendra Nath and Gupta, Vinod Kumar and Bachheti, Neeta and Sharma, Ram Avatar', 'abstract': 'A fullerene?C60?modified gold electrode is employed for the determination of dopamine in the excess of ascorbic acid using square?wave voltammetry. Based on its strong catalytic function towards the oxidation of dopamine and ascorbic acid, the overlapping voltammetric …', 'eprint': 'http://www.academia.edu/download/3909892/Dopamene.pdf', 'publisher': 'Wiley Online Library', 'year': '2008', 'pages': '757--764', 'number': '7', 'volume': '20', 'journal': 'Electroanalysis: An International Journal Devoted to Fundamental and Practical Aspects of Electroanalysis', 'ENTRYTYPE': 'article', 'ID': 'goyal2008electrochemical'}

# the CSV writer object
writer = csv.DictWriter("file.csv", fieldnames=[a, b, c],  dialect='toMYSQL')

# this is the source of the problem!
writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)

我了解容器仅具有裸露的骨骼,这意味着也许不支持脚本使用的编码。因此,我将其添加到脚本的开头:

# coding=utf-8
Run Code Online (Sandbox Code Playgroud)

这些是我的docker上的语言环境:

$ locale -a

C
C.UTF-8
POSIX
en_US.utf8
es_CR.utf8
Run Code Online (Sandbox Code Playgroud)

我的PC上还有更多功能,但这应该不会有太大变化,因为en_US.utf8涵盖了所有英语内容,而es_CR.utf8涵盖了所有西班牙语内容。(我的大部分(即使不是全部)结果都是英语。

我正在使用python3,所以我知道所有字符串都是unicode字符,也许多数民众赞成与问题有关?

$ python3 --version
Python 3.6.5
Run Code Online (Sandbox Code Playgroud)

尽管如此,当我运行程序时,脚本尝试在控制台上打印行时,我会收到以下错误消息:

Exception in thread Thread-6:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/Systematic-Mapping-Engine/sysmapengine/scraper.py", line 100, in build_csv
    writer.writerow(clean_row)
  File "/usr/lib/python3.6/csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character '\u2010' in position 262: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

yor*_*odm 6

大多数容器以LANG=Cset 开头。如果您要使用UTF-8,那可能会很烦人。

只是为了确保-e LANG=C.UTF-8在调用docker时,您的容器以正确的语言环境开头。

  • 在 Dockerfile 中:ENV LANG C.UTF-8 (11认同)