Skip to content

Instantly share code, notes, and snippets.

@Midnighter
Created February 20, 2017 15:23
Show Gist options
  • Save Midnighter/bc71a9b9eee797b7c2e3dfc45bb5dfa9 to your computer and use it in GitHub Desktop.
Save Midnighter/bc71a9b9eee797b7c2e3dfc45bb5dfa9 to your computer and use it in GitHub Desktop.
Insert standardized Python headers into one or more files.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Insert standardized Python headers into one or more files."""
from __future__ import (absolute_import, print_function)
import io
import re
import sys
def insert_coding_comment(
path,
coding_pattern=re.compile("^[ tv]*#.*?coding[:=][ t]*([-_.a-zA-Z0-9]+)"),
shebang=u"#!/usr/bin/env python\n",
coding=u"# -*- coding: utf-8 -*-\n"
):
"""
Insert the shebang and coding comment appropriately into given files.
Parameters
----------
path : str or path
The path to the Python module that should be modified.
coding_pattern : regex
A compiled regular expression that matches the encoding comment.
shebang : str
The shebang to insert if there was one present in the file.
coding : str
The encoding comment to insert in the first or second line.
"""
assert path.endswith(".py")
with io.open(path, "r") as file_h:
content = file_h.readlines()
line_index = 0
if content[line_index].startswith("#!"):
content[line_index] = shebang
line_index += 1
if coding_pattern.match(content[line_index]):
content[line_index] = coding
else:
content.insert(line_index, coding)
with io.open(path, "w") as file_h:
file_h.writelines(content)
def main(files):
"""Insert appropriate headers into one or more Python files."""
for filename in files:
try:
insert_coding_comment(filename)
except IOError as err:
print(str(err))
except IndexError as err:
print(filename)
print(str(err))
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment