python - 通过在 PyCharm 2016.3.2 中运行的 Python 3.6 脚本打开 UTF-8 编码的文件

标签 python python-3.x encoding utf-8 pycharm

我在使用 PyCharm 和我正在开发的 Python 应用程序时遇到了一个非常奇怪的问题。

  • Pycharm 是 PyCharm 社区版 2016.3.2
  • 项目解释器是:3.6.0
  • 操作系统是 MacOS Sierra

因为我已经在谷歌上搜索解决方案有一段时间了,但没有提出的想法对我有帮助,我想在这里询问。

我想使用以下代码打开 UTF-8 编码的文件:

#!/usr/bin/env python3    

import os, platform

def read(file):
    f = open(file, "r")
    content = f.read()
    f.close()
    return content

print(platform.python_version())
print(os.environ["PYTHONIOENCODING"])

content = read("testfile")
print(content)

代码在 PyCharm 中运行时崩溃。输出是

3.6.0
UTF-8
Traceback (most recent call last):
  File "/Users/xxx/Documents/Scripts/pycharmutf8/file.py", line 14, in <module>
    content = read("testfile")
  File "/Users/xxx/Documents/Scripts/pycharmutf8/file.py", line 7, in read
    content = f.read()
  File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

当我从命令行运行相同的代码时,它工作得很好:

./file.py 
3.6.0
utf-8:surrogateescape
I am a file with evil unicode characters: äöü

我发现,在类似的情况下,建议人们将环境变量 PYTHONIOENCODING 设置为 utf-8:surrogateescape (正如您在上面看到的那样)输出)全系统

export PYTHONIOENCODING=utf-8:surrogateescape

而且也在 PyCharm 本身中(设置 -> 构建 -> 控制台 -> Python 控制台 -> 环境变量)。

这没有任何效果。您还有进一步的建议吗?

最佳答案

如果更改开放调用的编码比较困难,即它发生在库中,您可以在运行配置中更改此环境变量:LC_CTYPE=en_US.UTF-8

来源: PyCharm is changing the default encoding in my Django app

关于python - 通过在 PyCharm 2016.3.2 中运行的 Python 3.6 脚本打开 UTF-8 编码的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811647/

相关文章:

python - 如何在 python 脚本中修改系统路径变量?

python - 当两个单词之一发生变化时,在 Python 中查找两个指定单词之间的文本

python - 在 Ubuntu 上使用 sao 安装 Tryton ERP

python-3.x - 使用 pytest,如何将 pathlib 的 Path.isdir() 函数与 os.listdir 一起模拟

scala - 如何让 scala-maven-plugin 识别 Cp1252 编码?

java - 构建基于 Java 的多语言 Web 应用程序的最佳编码是什么?为什么?

python - 如何在 Python 中实现 Perl 的 exec 功能?

python 3 : Print multiple lines to one line

python - TypeError : expected str, 字节或 os.PathLike 对象,而不是 _io.BytesIO

javascript - 谷歌+网址分享