为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding("utf-8") ? [英] Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

查看:19
本文介绍了为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding("utf-8") ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很少有 py 脚本在脚本的顶部使用它.在什么情况下应该使用它?

I have seen few py scripts which use this at the top of the script. In what cases one should use it?

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

推荐答案

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

As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.

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

This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py, After this module has been evaluated, the setdefaultencoding() function is removed from the sys module.

实际使用它的唯一方法是使用重新加载黑客将属性带回来.

The only way to actually use it is with a reload hack that brings the attribute back.

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

Also, the use of sys.setdefaultencoding() has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.

我建议一些阅读要点:

这篇关于为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding("utf-8") ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆