views:

33

answers:

2

How can I tell the encoding of the source file from inside a running python process, if it is even possible?

A: 

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.

Ned Batchelder
Ned, I meant programmatically :) I should been more clear!
Gregg Lind
Ned, I shudder to even mention it. I am working on a dual 2/3 codebase that has lots of byte comparisons, and I would like to work around the b'' literal. So, things get instead bytes('string'.encode(ENCODING)'), and other horrors. At least I hope it will be contained in one place!
Gregg Lind
+1  A: 

encoding = open(__file__).encoding

This might work in some circumstances, but take note of http://docs.python.org/library/stdtypes.html#file.encoding

nieldw