我见过一些在脚本顶部使用它的 py 脚本。在什么情况下应该使用它?
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
最佳答案
根据文档:这允许您从默认 ASCII 切换到其他编码,例如 UTF-8,Python 运行时将在必须将字符串缓冲区解码为 unicode 时使用该编码。
此功能仅在 Python 启动时可用,此时 Python 扫描环境。它必须在系统范围的模块 sitecustomize.py
中调用,在评估此模块后,setdefaultencoding()
函数将从 sys 中删除
模块。
真正使用它的唯一方法是使用重新加载技巧来恢复属性。
另外,一直不鼓励使用sys.setdefaultencoding()
,它已经成为py3k中的空操作。 py3k 的编码是硬连线到“utf-8”,更改它会引发错误。
我建议一些阅读指南:
关于python - 为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding ("utf-8")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3828723/