在 VS Code 中以错误编码保存的文本文件(在 Ubuntu 上)导致 unicode 错误

Textfile saved in wrong encoding in VS Code (on Ubuntu) leading to unicode error

我正在使用 Lubuntu 18.04 下的 Visual Studio 代码。 VS Code 中的文件编码配置为 UTF-8,Python 脚本的编码设置为 utf-8:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

Python 文件包含一些非 ASCII 字符,如本示例文档字符串中所示:

"""
'Al final pudimos reparar el problema de registro de datos y se pudieron montar los
equipos para recoger algún dato más. ...'
"""

如果执行脚本,我会收到以下错误:

SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xfa in position 141: invalid start byte

这是回溯:

Traceback (most recent call last):
  File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/USERNAME/.vscode/extensions/ms-python.python-2020.6.90262/pythonFiles/lib/python/debugpy/__main__.py", line 45, in <module>
    cli.main()
  File "/home/USERNAME/.vscode/extensions/ms-python.python-2020.6.90262/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 430, in main
    run()
  File "/home/USERNAME/.vscode/extensions/ms-python.python-2020.6.90262/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 267, in run_file
    runpy.run_path(options.target, run_name=compat.force_str("__main__"))
  File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/runpy.py", line 261, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
  File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/runpy.py", line 236, in _get_code_from_file
    code = compile(f.read(), fname, 'exec')
  File "/home/USERNAME/Desktop/Python/Scripts/General/Import_export/import_EXCEL_spreadsheet_data_write_to_CSV.py", line 338
众多提案中的

None 对我有用,因为在执行任何包含非 ASCII 字符的 Python 脚本时会抛出此错误,即使在注释或文档字符串中也是如此。

找到问题原因后编辑

可以找到实际答案。 尽管如此,假设某些信息仍然有用,我不会删除以下原始解决方法和相关评论中所述的内容。

原始解决方法

在有人想出更优雅、切题的方法之前,我将分享我的 解决方法,它为我解决了问题:

  1. 确定您实际需要的语言:在我的例子中,我用英语编写代码,但有时我可能需要用德语(元音变音如“ääöüöü”)或西班牙语(重音如“á, ú” , ..") 这意味着某些 latin-non-ASCII 个字符。
  2. 由于 utf-8 在与我的问题有关的评论中概述的未知原因在我的系统上不起作用,因此将所有 python 中的 # -*- coding: utf-8 -*- 替换为 # -*- coding: latin-1 -*--脚本在需要的地方,甚至是默认的。

完成第 2 步的备选方案如下:

  • 通过右上角的放大镜搜索VS Code目录下的所有文件,或. Hereby, it might be interesting to exclude the **/.history/** folder-pattern .
  • 使用 CLI 方法 sed 进行搜索和替换任务。

总的来说,这对我有用。我可以知道在我的脚本中键入“ääöüöü”和“á,ú,...”并保存它们而不会在 VS Code.

中出现任何错误

终于找到了整个问题的原因: 它位于 settings.json - 文件中,其中 设置为 true:

"files.autoGuessEncoding": true

此选项能够覆盖 "files.encoding": "utf8",因此即使您定义了首选编码,VS Code 也能够猜测另一种编码。 凭借 Brett Cannon 的宝贵提示,我发现确实在 VS Code 的右下角,文件的编码有时(自动)设置为 Windows 1252。对 VS Code 选项 "files.autoGuessEncoding": true 的不幸猜测导致了我最初问题中提到的上述常见错误(前提是我插入了变音符号(“äöü..”)或变音符号(“éúá..”)在我脚本的某处):

  1. 插入后立即在 pylint 中获取 错误消息:"error while code parsing: Wrong or no encoding specified for script.py."
  2. 接下来,运行 脚本 生成提到的 SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xfa in position 141: invalid start byte

正如在与上述 相关的讨论中所述,VS Code 在检测适当的文件编码方面仍然有些 不准确 ,我可以确认。

为了最终解决这个问题,通过在 settings.json 中添加以下两行来避免自动检测(或在 VS Code 的设置-GUI 中设置相关选项):

{...,

    "files.encoding": "utf8",
    "files.autoGuessEncoding": false,
...

}

现在,可以在文本文件或脚本中放置任何想要的字符,例如变音符号(“äöü..”)和变音符号(“éúá..”)。

最后,值得注意的是,上述设置不会更改先前已创建和保存的文件的编码。 为此,您需要左键单击 VS Code window 右下角的编码,然后使用所需的编码 reopensave,这很可能是 utf8.

关于设置,请注意您也可以通过 File -> Preferences -> Settings 下的 GUI 更改这些设置,而不是使用 settings.json - 文件(通过 Ctrl + Shift + P 然后 "Preferences: Open Settings (JSON)".