def write_py2k_header(file_list):
if not isinstance(file_list, list):<EOL><INDENT>file_list = [file_list]<EOL><DEDENT>python_re = re.compile(br"<STR_LIT>")<EOL>coding_re = re.compile(br"<STR_LIT>")<EOL>new_line_re = re.compile(br"<STR_LIT>")<EOL>version_3 = LooseVersion('<STR_LIT:3>')<EOL>for file in file_list:<EOL><INDENT>if not os.path.getsize(file):<EOL><INDENT>continue<EOL><DEDENT>rewrite_needed = False<EOL>python_found = False<EOL>coding_found = False<EOL>lines = []<EOL>f = open(file, '<STR_LIT:rb>')<EOL>try:<EOL><INDENT>while len(lines) < <NUM_LIT:2>:<EOL><INDENT>line = f.readline()<EOL>match = python_re.match(line)<EOL>if match:<EOL><INDENT>python_found = True<EOL>version = LooseVersion(match.group(<NUM_LIT:2>).decode() or '<STR_LIT:2>')<EOL>try:<EOL><INDENT>version_test = version >= version_3<EOL><DEDENT>except TypeError:<EOL><INDENT>version_test = True<EOL><DEDENT>if version_test:<EOL><INDENT>line = python_re.sub(br"<STR_LIT>", line)<EOL>rewrite_needed = True<EOL><DEDENT><DEDENT>elif coding_re.search(line):<EOL><INDENT>coding_found = True<EOL><DEDENT>lines.append(line)<EOL><DEDENT>if not coding_found:<EOL><INDENT>match = new_line_re.search(lines[<NUM_LIT:0>])<EOL>newline = match.group(<NUM_LIT:1>) if match else b"<STR_LIT:\n>"<EOL>line = b"<STR_LIT>" + newline<EOL>lines.insert(<NUM_LIT:1> if python_found else <NUM_LIT:0>, line)<EOL>rewrite_needed = True<EOL><DEDENT>if rewrite_needed:<EOL><INDENT>lines += f.readlines()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT>if rewrite_needed:<EOL><INDENT>f = open(file, '<STR_LIT:wb>')<EOL>try:<EOL><INDENT>f.writelines(lines)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT><DEDENT>
Write Python 2 shebang and add encoding cookie if needed.