2

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

2 Answers 2

2

encoding = open(__file__).encoding

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.