python - 为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding

我见过一些在脚本顶部使用它的 py 脚本。在什么情况下应该使用它?

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

最佳答案

根据文档:这允许您从默认 ASCII 切换到其他编码,例如 UTF-8,Python 运行时将在必须将字符串缓冲区解码为 un​​icode 时使用该编码。

此功能仅在 Python 启动时可用,此时 Python 扫描环境。它必须在系统范围的模块 sitecustomize.py 中调用,在评估此模块后,setdefaultencoding() 函数将从 sys 中删除 模块。

真正使用它的唯一方法是使用重新加载技巧来恢复属性。

另外,一直不鼓励使用sys.setdefaultencoding(),它已经成为py3k中的空操作。 py3k 的编码是硬连线到“utf-8”,更改它会引发错误。

我建议一些阅读指南:

  • http://blog.ianbicking.org/illusive-setdefaultencoding.html
  • http://nedbatchelder.com/blog/200401/printing_unicode_from_python.html
  • http://www.diveintopython3.net/strings.html#one-ring-to-rule-them-all
  • http://boodebr.org/main/python/all-about-python-and-unicode
  • http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

关于python - 为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding ("utf-8")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3828723/

相关文章:

python - isinstance ('aaa' , basestring) 和 isinsta

linux - 确保只有一个 Bash 脚本实例正在运行的最佳方法是什么?

linux - CURL 用于访问需要从其他页面登录的页面

python - 安装pycurl时出现"Could not run curl-config: [E

python - 在 Python 脚本中,如何设置 PYTHONPATH?

python - virtualenv和pyenv是什么关系?

shell - 如何将文本 append 到文件?

linux - 如何使用 Red Hat Linux 上的标准工具随机化文件中的行?

python - 如何以正确的方式平滑曲线?

unix - 创建守护进程时执行双叉的原因是什么?