- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否有可用的 Python 脚本来搜索文件并自动将所有文本包装在注释 block 中?我要:
我不认为 autopep8 做 2,如果我错了请纠正我。我正在使用 PyCharm,它的自动格式选项也不执行 2。
我很想编写自己的脚本来执行此操作,因为我认为这不会花费很长时间,但我想先与社区核实一下。
最佳答案
我找不到执行此操作的脚本。我自己写了一个使用 textwrap 的。空注释行被跳过,包含“=========”或“--------”的行被视为特殊情况并被跳过,例如:
# =============================================================================
# Code Block
# =============================================================================
被跳过。该脚本还包装了文档字符串。这是在 Windows 中的 Python 2.7 中测试的代码,使用风险自负:
#!/usr/bin/env python
# =====================================================================================================================
#
# Overview: This script takes as input a python script and automatically wraps all comment blocks and docstrings.
#
# Usage: Run python <script_name>.py -h to see the usage of this script.
#
# =====================================================================================================================
# =====================================================================================================================
# Imports
# =====================================================================================================================
import sys
import os
import shutil
import textwrap
# =====================================================================================================================
# Constants
# =====================================================================================================================
# All possible script return values.
EXIT_OK = 0
EXIT_ERROR = 1
# The number of characters allowed on a single line.
LINE_LENGTH = 119
# =====================================================================================================================
# File Global Variables
# =====================================================================================================================
#
# (Currently none)
#
# =====================================================================================================================
# Functions
# =====================================================================================================================
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)
# =====================================================================================================================
# Script's Main Function
# =====================================================================================================================
def main():
""" This function is the main entry point of the script. """
# Check if this version of Python meets the minimum requirement for this
# script. Currently the version dependencies are:
# 1) v2.6 is needed for the print() function (print() is required in v3.0
# and greater).
# 2) v2.7 is needed for the argparse module.
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
# Enumerate the states we can be in.
(
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:]
# Skip the first "shebang" line.
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()
# Check if this a blank line.
if comment != "":
# It's not a blank line, continue trying to read the subsequent comment lines, if any.
state = READING_COMMENT
else:
# It is a blank line, flush the line, and don't change the state.
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()
# Check if this a blank line.
if comment_line != "":
# It's not a blank line, continue trying to read the subsequent comment lines, if any.
comment += " " + line[comment_start_index + 1:].strip()
else:
# It is a blank line, write the comment, and flush the line.
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())
关于python - 自动格式化 Python 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622167/
我正在从事的项目需要使用 toString 方法打印银行帐户余额。我不允许向当前程序添加任何方法,但我需要将 myBalance 变量格式化为 double 型,该变量保留两位小数而不是一位。在这个特
我喜欢 Visual Studio (2008) 格式化 C# 代码的方式;不幸的是,在编写 C++ 代码时,它的行为方式似乎有所不同。 比如我这样写代码的时候: class Test { publi
Scanner scan = new Scanner(System.in); System.out.println("Enter three positive integers seperated b
在 aspose(使用 C#)中用于格式化数字的正确样式属性是什么。我想做两件事: 1) 将五位数字格式化为邮政编码。(我不太确定使用哪个 Style 属性来获取自定义 excel 邮政编码格式) 2
我希望用户输入从 00 到 23 和从 00 到 59 的 Local.Time 的小时和分钟,我将其扫描为一个 int。它有效,但对于从 00 到 09 的值,int 忽略 0,然后将其放置为 0,
大家好, 请查看上面的图片,我有两张 table 。在下面代码的第一个表中,我得到了这种格式。 但我想像 Table2 那样格式化,每个合并单元格中的行数是动态的,而且不一样。 有没有办法像table
我在一个 laravel 网站工作,我只是想知道是否有办法为用户格式化 created_at 值,因为现在它类似于以下内容: 2017-09-20 13:41 但我更愿意将其格式化为易于阅读的格式,例
我正在尝试在 JTextPane 中进行一些基本的格式化。为此,我决定使用 html(HTMLDocument 和 HTMLEditorKit)。 这里是按钮的操作监听器代码,应使所选文本变为粗体 b
是否有规则或插件会导致 es-lint 错误或警告,如果范围内的声明没有像下面那样间隔,赋值运算符的对齐方式相同? var a = 'a'; var bb = 'b'; var ccc = 'd
我正在尝试重新格式化 LinkedHashMap 的输出以排除逗号和大括号。 这是我的看跌期权: token.put("[Server.Protocol]", url.getProtocol() +
我有一个程序,可以从文本文件中读取大量文本,然后根据文本内容随机化内容以显示为短篇故事。该程序可以运行,但最后一部分(我显示的 Material )非常笨重且效率不高,我想知道是否有人对如何更有效地获
我正在尝试将 VIM 作为我的 ruby/rails 编辑器。太胖了,我对它的功能印象深刻 并且我能够安装以下插件以提供更好的 IDE 体验 自动配对 Better-snipmate-snippe
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我有两个 jQuery 函数。我想先运行下面的第一个,然后在该函数完成后运行另一个。通常我会在代码的第一部分添加一个函数,但不确定如何使用这个 block 来做到这一点,或者它是否是正确的方法。 简而
在 Python 2.7 中,我有一个包含数字 1-25 字符串的列表(例如)。打印它们时,我希望列表打印 5 行,每行 5 个数字。 理想情况下: >>> print(myList) ['1', '
我有以下功能来打印借阅者已取出的书籍列表。 void searchBorrowerLoans(int a) { int i; for (i = 1
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 5 年前。 Improv
我正在尝试实现一个用作 ListView header 的 TextView。我想对其进行格式化,以便我基本上有一个以第一行为中心的标题,然后是以下几行的附加信息。如何格式化文本/字符串以创建这种格式
我尝试格式化数字字段 select to_char(12315.83453, 'FM999999999999D9999') 在这种情况下一切正常。结果是 12315.8345 但是如果值在0到1之间
我有一个带有 BigDecimal 字段的类。我把这个对象放到 JSP(Spring MVC)中。而且我需要显示十进制不带零的 BigDecimal 字段(20.00 就像 20),这就是为什么我的
我是一名优秀的程序员,十分优秀!