Get CURRENT_FILE_ENCODING for a python file or environment
How can I tell the enco开发者_C百科ding of the source file from inside a running python process, if it is even possible?
encoding = open(__file__).encoding
This might work in some circumstances, but take note of http://docs.python.org/library/stdtypes.html#file.encoding
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.
精彩评论