获取 python 文件或环境的 CURRENT_FILE_ENCODING
如果可能的话,如何从正在运行的 python 进程内部判断源文件的编码?
How can I tell the encoding of the source file from inside a running python process, if it is even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
encoding = open(__file__).encoding
这在某些情况下可能有效,但请注意
encoding = open(__file__).encoding
This might work in some circumstances, but take note of http://docs.python.org/library/stdtypes.html#file.encoding
如果您检查
__file__
,它将为您提供正在运行的代码的文件名。如果它以“.pyc”或“.pyo”结尾,则剪掉最后一个字符。这是运行代码的源文件。读取该文件,查找编码标头。请注意,这是一种简化,找到真正的源文件可能会变得更加困难,但这在许多情况下都有效。
BTW:为什么需要知道源文件的编码?我想,这应该是无关紧要的。
If you examine
__file__
, it will give you the file name of the running code. If it ends in ".pyc" or ".pyo", clip off the last character. This is the source file of the running code. Read that file, looking for the encoding header.Note that this is a simplification, and it can get much harder to find the real source file, but this will work in many cases.
BTW: Why do you need to know the encoding of the source file? It should be irrelevant, I would have thought.