【问题标题】:Why does my `write` give UnicodeDecodeError on OSX but not Linux? [closed]为什么我的 `write` 在 OSX 上给出 UnicodeDecodeError 而不是 Linux? [关闭]
【发布时间】:2018-02-23 09:26:57
【问题描述】:

我在 scons 构建文件中有这段代码:

with io.open(target[0].get_path(), 'w', encoding="utf-8") as target_file:
            target_file.write( unicode("std::string {} = R\"~~~~({})~~~~\";").format(varName,content))

content 变量将包含非 ascii 字符。在 OSX 上我没有问题,但在 Linux 上我收到 UnicodeDecodeError: 'ascii' codec can't decode byte 错误。

奇怪的是,如果我只使用 open,请删除编码,并删除 unicode 位,相反的情况会发生:它适用于 Linux 而不是 OSX。

with open(target[0].get_path(), 'w') as target_file:
    target_file.write( "std::string {} = R\"~~~~({})~~~~\";".format(varName,content))

出了什么问题,我该如何解决?

版本:

  • OSX Python:2.7.10
  • OSX Scons:3.0.1
  • Linux Python:2.7.12
  • Linux Scons:2.4.1

【问题讨论】:

  • @Jean-FrançoisFabre 这个问题应该可以在没有完整复制的情况下回答。这是一个关于正确使用 Python 和理解问题所在的问题。
  • 如果没有minimal reproducible example,我们就无法提供肯定的答案。这并不难。只需将 contents 和 varname 分配给触发错误的某个值即可。要求不高,帮我们帮你
  • 我不需要一个确定的答案。我正在寻找可以指出潜在原因的任何人,例如系统编码或其他。我很乐意跟进细节。

标签: python macos python-2.7 scons


【解决方案1】:

format() 当您作为参数传递的某些变量包含非 ascii 字符,而基本字符串是 ascii 时,有时会以这种方式失败。

关于为什么它会在 OSX 而不是 Linux 上运行,每个操作系统都有处理字符编码的特定方法,这可能会导致此类问题。

试试这个:

"your sting {} ".encode('utf-8').format(.....

【讨论】:

  • 谢谢。我对两者都做.encode('utf-8') on all strings, and it works on OSX's version, but now fails on Linxu. Default encoding is ascii`。我会进一步调查。
  • 尝试也编码你给格式的变量,可能会奏效。 (变量名称和内容)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2014-11-06
  • 2018-06-27
  • 1970-01-01
相关资源
最近更新 更多