7
(codecs.BOM_UTF8, 'utf8'),
8
(codecs.BOM_UTF16, 'utf16'),
9
(codecs.BOM_UTF16_BE, 'utf16-be'),
10
(codecs.BOM_UTF16_LE, 'utf16-le'),
11
(codecs.BOM_UTF32, 'utf32'),
12
(codecs.BOM_UTF32_BE, 'utf32-be'),
13
(codecs.BOM_UTF32_LE, 'utf32-le'),
16
ENCODING_RE = re.compile(b'coding[:=]\s*([-\w.]+)')
19
def auto_decode(data):
20
"""Check a bytes string for a BOM to correctly detect the encoding
22
Fallback to locale.getpreferredencoding(False) like open() on Python3"""
23
for bom, encoding in BOMS:
24
if data.startswith(bom):
25
return data[len(bom):].decode(encoding)
26
# Lets check the first two lines as in PEP263
27
for line in data.split(b'\n')[:2]:
28
if line[0:1] == b'#' and ENCODING_RE.search(line):
29
encoding = ENCODING_RE.search(line).groups()[0].decode('ascii')
30
return data.decode(encoding)
31
return data.decode(locale.getpreferredencoding(False))