【问题标题】:Travis CI encodes ü as üTravis CI 将 ü 编码为 ü
【发布时间】:2016-08-25 15:29:58
【问题描述】:

我正在用 Python 将一些 Unicode 字符串写入 HTML。我这样做的方式是在内部使用 Unicode,并且只在输出时进行编码。所以像:

with open(filename, 'w') as f:
    f.write(s.encode("utf-8"))

这在我的本地机器上可以正常工作。但是当它放到 Travis CI 上时,生成的文件有 ü 代替 ü。有什么想法吗?

这是我的.travis.yml

language: python
python: 2.7.10
install: pip install -r requirements.txt
script: python main.py -d
deploy:
  provider: s3
  access_key_id: XXX
  secret_access_key:
    secure: XXX
  bucket: www.my.org
  region: us-east-1
  skip_cleanup: true
  default_text_charset: 'utf-8'
  local-dir: output

更新

可以重现该问题的最小 Python 代码如下:

from pyquery import PyQuery as pq

argurl = 'http://hackingdistributed.com/tag/bitcoin/'

d = pq(url=argurl)

authors = []
for elem in d.find("h2.post-title a"):
    pubinfo = pq(elem).parent().parent().find(".post-metadata .post-published")
    author = pq(pubinfo).find(".post-authors").html().strip()
    authors.append(author)

with open('output/test.html', 'w') as f:
    f.write(': '.join(authors).encode('utf-8'))

查看output/test.html 以查看ü

【问题讨论】:

  • 能否附上您正在使用的.travis-ci.yml 以及最小的 Python 示例代码?
  • @tambre 请查看我的编辑。
  • 你在本地使用的是什么 Python 版本?
  • @tambre Python 2.7.10
  • 我怀疑这是您的 Python 代码中的一个错误。您介意在 Travis 上发布能够重现此问题的最少量 Python 代码吗?

标签: python unicode travis-ci python-unicode


【解决方案1】:

这似乎是因为您的浏览器可能错误地读取了文件。最简单的解决方法是通过在文件开头添加 BOM 标记将其编码为 UTF-8 BOM。

这是写入文件的固定代码:

with open('output/test.html', 'w') as f:
    f.write(u'\ufeff'.encode('utf-8')) # BOM marker
    f.write(': '.join(authors).encode('utf-8'))

【讨论】:

  • 并非如此。正如评论中所说,现在我怀疑urlib 可能是问题所在。似乎它将原始网站读取为 Latin-1 并返回 UTF-8 编码的“Latin-1”字符串。有什么想法吗?
  • @qweruiop 你不在代码中的任何地方使用urllib...?
  • pyquery 使用 urblib。
猜你喜欢
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2020-11-10
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多