Python source files often come with a coding header similar to the following
# -*- coding: iso-8859-1 -*-
How can I this line to properly parse the contents of such a file? Is there a better way than manually opening the file in binary mode, reading one line, and checking if it contains the header? Is there a library that does this?
Background: this comes in the context of fixing this bug, which crashes elpy when used in conjunction with python3 and importmagic. The code that I'm trying to fix uses
with open(filename) as fd:
success = subtree.index_source(filename, fd.read())
and crashes on non-utf-8 files. Ideally I would like to keep changes to a minimum.