我找不到一个能做这个的脚本。我写了一个自己的,使用textwrap。空注释行会被跳过,而包含“=========”或“---------”的行则被视为特殊情况并被跳过,例如:
被跳过。该脚本还包装docstrings。以下是代码,在Windows中测试了Python 2.7,使用需谨慎:
import sys
import os
import shutil
import textwrap
EXIT_OK = 0
EXIT_ERROR = 1
LINE_LENGTH = 119
def parse_arguments():
""" This function parses the command line arguments and returns the user-specified configuration options. """
import argparse
parser = argparse.ArgumentParser(description="Auto-format comments and docstrings.")
parser.add_argument(
"input",
help="input file")
parser.add_argument(
"-o", "--out",
help="output file, input file modified in-place if not specified")
args = parser.parse_args()
return EXIT_OK, args.input, args.out
def _print_message(message_type, message):
""" This function prints a message formatted to display well in an 80 character terminal. """
print(textwrap.fill(
(message_type + ": ").ljust(max(len("Error"), len("Warning"), len("Status")) + 2) + message,
initial_indent="",
subsequent_indent=" ",
width=79))
def print_error(message):
""" This function prints an error message. """
_print_message("Error", message)
def print_warning(message):
""" This function prints a warning message. """
_print_message("Warning", message)
def print_status(message):
""" This function prints a status message. """
_print_message("Status", message)
def print_status_pending_begin(message):
""" This function prints a message to notify the user that an action has started and is pending completion. """
sys.stdout.write("Status: " + message.ljust(41, "."))
def print_status_pending_end(message):
""" This function prints a message to notify the user a pending action has completed. """
print(" " + message)
def write_comment(file_handle, comment_whitespace_prefix, comment, line_ending_str):
""" This function writes a comment to the specified output file handle. """
line_start_str = comment_whitespace_prefix + "# "
comment_lines = textwrap.wrap(
comment,
initial_indent=line_start_str,
subsequent_indent=line_start_str,
width=LINE_LENGTH)
for line in comment_lines:
file_handle.write(line + line_ending_str)
def write_doc_string(file_handle, comment_whitespace_prefix, comment, line_ending_str):
""" This function writes a doc string to the specified output file handle. """
if (len(comment_whitespace_prefix) + len(comment) + len('""" ') + len(' """')) <= LINE_LENGTH:
file_handle.write(comment_whitespace_prefix + '""" ' + comment + ' """' + line_ending_str)
else:
file_handle.write(comment_whitespace_prefix + '"""' + line_ending_str)
comment_lines = textwrap.wrap(
comment,
initial_indent=comment_whitespace_prefix,
subsequent_indent=comment_whitespace_prefix,
width=LINE_LENGTH)
for line in comment_lines:
file_handle.write(line + line_ending_str)
file_handle.write(comment_whitespace_prefix + '"""' + line_ending_str)
def main():
""" This function is the main entry point of the script. """
if sys.hexversion < 0x02070000:
print_error("This script requires Python v2.7 or greater.")
return EXIT_ERROR
return_value, input_file, output_file = parse_arguments()
if return_value != EXIT_OK:
return return_value
input_file = os.path.abspath(input_file)
if not os.path.exists(input_file):
print_error("Input file " + input_file + " does not exist.")
if output_file is None:
split_path = os.path.split(input_file)
output_file = os.path.join(split_path[0], "__temp__" + split_path[1])
modify_in_place = True
else:
modify_in_place = False
(
SEARCHING_COMMENT_START,
READING_COMMENT,
READING_DOCSTRING,
SKIPPING_COMMENT
) = range(4)
with open(input_file, "rb") as input_file_handle:
with open(output_file, "wb") as temp_output_file_handle:
line_ending_str = None
state = SEARCHING_COMMENT_START
for line in input_file_handle:
if line_ending_str is None:
index = -1
while (line[index] == "\r") or (line[index] == "\n"):
index -= 1
line_ending_str = line[index + 1:]
if line.startswith("#!"):
temp_output_file_handle.write(line)
continue
lstripped_line = line.lstrip()
if state == SEARCHING_COMMENT_START:
if lstripped_line.startswith("#"):
if ("=================" not in lstripped_line) and ("-----------------" not in lstripped_line):
comment_start_index = line.index("#")
comment_whitespace_prefix = line[:comment_start_index]
comment = line[comment_start_index + 1:].strip()
if comment != "":
state = READING_COMMENT
else:
temp_output_file_handle.write(line)
else:
temp_output_file_handle.write(line)
state = SKIPPING_COMMENT
elif lstripped_line.startswith('"""'):
comment_start_index = line.index('"""')
comment_whitespace_prefix = line[:comment_start_index]
comment = line[comment_start_index + len('"""'):].strip()
if not comment.endswith('"""'):
if comment == "":
doc_string_separator = ""
else:
doc_string_separator = ""
state = READING_DOCSTRING
else:
comment = comment.rsplit('"""', 1)[0].rstrip()
write_doc_string(temp_output_file_handle, comment_whitespace_prefix, comment,
line_ending_str)
else:
temp_output_file_handle.write(line)
elif state == READING_COMMENT:
if lstripped_line.startswith("#"):
comment_start_index = line.index("#")
comment_line = line[comment_start_index + 1:].strip()
if comment_line != "":
comment += " " + line[comment_start_index + 1:].strip()
else:
write_comment(temp_output_file_handle, comment_whitespace_prefix, comment, line_ending_str)
temp_output_file_handle.write(line)
state = SEARCHING_COMMENT_START
else:
write_comment(temp_output_file_handle, comment_whitespace_prefix, comment, line_ending_str)
temp_output_file_handle.write(line)
state = SEARCHING_COMMENT_START
elif state == READING_DOCSTRING:
if '"""' not in lstripped_line:
comment += doc_string_separator + lstripped_line.rstrip()
doc_string_separator = " "
else:
comment += (doc_string_separator + lstripped_line).rsplit('"""', 1)[0].rstrip()
write_doc_string(temp_output_file_handle, comment_whitespace_prefix, comment, line_ending_str)
state = SEARCHING_COMMENT_START
elif state == SKIPPING_COMMENT:
temp_output_file_handle.write(line)
if "#" not in line:
state = SEARCHING_COMMENT_START
else:
raise Exception("Unknown state, check script's logic.")
if modify_in_place:
shutil.move(output_file, input_file)
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())