def parse_encoding(fp):
 pos = fp.tell()
 fp.seek(0)
 try:
  line1 = fp.readline()
  has_bom = line1.startswith(codecs.BOM_UTF8)
  if has_bom:
   line1 = line1[len(codecs.BOM_UTF8):]
  m = PYTHON_MAGIC_COMMENT_re.match(line1)
  if (not m):
   try:
    import parser
    parser.suite(line1)
   except (ImportError, SyntaxError):
    pass
   else:
    line2 = fp.readline()
    m = PYTHON_MAGIC_COMMENT_re.match(line2)
  if has_bom:
   if m:
    raise SyntaxError('python refuses to compile code with both a UTF8 byte-order-mark and a magic encoding comment')
   return 'utf_8'
  elif m:
   return m.group(1)
  else:
   return None
 finally:
  fp.seek(pos)

def parse_encoding ( fp ) : pos = fp . tell ( ) fp . seek ( 0 ) try : line1 = fp . readline ( ) has_bom = line1 . startswith ( codecs . BOM_UTF8 ) if has_bom : line1 = line1 [ len ( codecs . BOM_UTF8 ) : ] m = PYTHON_MAGIC_COMMENT_re . match ( line1 ) if ( not m ) : try : import parser parser . suite ( line1 ) except ( ImportError , SyntaxError ) : pass else : line2 = fp . readline ( ) m = PYTHON_MAGIC_COMMENT_re . match ( line2 ) if has_bom : if m : raise SyntaxError ( 'python refuses to compile code with both a UTF8 byte-order-mark and a magic encoding comment' ) return 'utf_8' elif m : return m . group ( 1 ) else : return None finally : fp . seek ( pos )
deduce the encoding of a source file from magic comment .