我在Python 2.7中使用argparse来解析输入选项。我的选项之一是多项选择。我想在它的帮助文本中做一个列表。
from argparse import ArgumentParser
parser = ArgumentParser(description='test')
parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
help="Some option, where\n"
" a = alpha\n"
" b = beta\n"
" g = gamma\n"
" d = delta\n"
" e = epsilon")
parser.parse_args()
然而,argparse会删除所有换行和连续的空格。结果如下所示
~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]
test
optional arguments:
-h, --help show this help message and exit
-g {a,b,g,d,e} Some option, where a = alpha b = beta g = gamma d = delta e
= epsilon
如何在帮助文本中插入换行?
另一种简单的方法是包含文本包。
例如,
import argparse, textwrap
parser = argparse.ArgumentParser(description='some information',
usage='use "python %(prog)s --help" for more information',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--argument', default=somedefault, type=sometype,
help= textwrap.dedent('''\
First line
Second line
More lines ... '''))
通过这种方式,我们可以避免在每个输出行前面有很长的空白。
usage: use "python your_python_program.py --help" for more information
Prepare input file
optional arguments:
-h, --help show this help message and exit
--argument ARGUMENT
First line
Second line
More lines ...
使用RawTextHelpFormatter获取新行并处理缩进的另一种简单方法是
import argparse
parser = argparse.ArgumentParser(
description='test', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
help=('Some option, where\n'
' a = alpha\n'
' b = beta\n'
' g = gamma\n'
' d = delta\n'
' e = epsilon'))
parser.parse_args()
输出为
$ python2 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]
test
optional arguments:
-h, --help show this help message and exit
-g {a,b,g,d,e} Some option, where
a = alpha
b = beta
g = gamma
d = delta
e = epsilon
Bernd的回答非常有用,但不适用于参数帮助字符串。下面是它的一个扩展,适用于所有的帮助文本(遵循RawTextHelpFormatter的例子)。
WrappedNewlineFormatter是他最初的RawFormatter, WrappedNewlineFormatter将额外包装参数。
import argparse
import textwrap
class DescriptionWrappedNewlineFormatter(argparse.HelpFormatter):
"""An argparse formatter that:
* preserves newlines (like argparse.RawDescriptionHelpFormatter),
* removes leading indent (great for multiline strings),
* and applies reasonable text wrapping.
Source: https://stackoverflow.com/a/64102901/79125
"""
def _fill_text(self, text, width, indent):
# Strip the indent from the original python definition that plagues most of us.
text = textwrap.dedent(text)
text = textwrap.indent(text, indent) # Apply any requested indent.
text = text.splitlines() # Make a list of lines
text = [textwrap.fill(line, width) for line in text] # Wrap each line
text = "\n".join(text) # Join the lines again
return text
class WrappedNewlineFormatter(DescriptionWrappedNewlineFormatter):
"""An argparse formatter that:
* preserves newlines (like argparse.RawTextHelpFormatter),
* removes leading indent and applies reasonable text wrapping (like DescriptionWrappedNewlineFormatter),
* applies to all help text (description, arguments, epilogue).
"""
def _split_lines(self, text, width):
# Allow multiline strings to have common leading indentation.
text = textwrap.dedent(text)
text = text.splitlines()
lines = []
for line in text:
wrapped_lines = textwrap.fill(line, width).splitlines()
lines.extend(subline for subline in wrapped_lines)
if line:
lines.append("") # Preserve line breaks.
return lines
if __name__ == "__main__":
def demo_formatter(formatter):
parser = argparse.ArgumentParser(
description="""
A program that does things.
Lots of description that describes how the program works.
very long lines are wrapped. very long lines are wrapped. very long lines are wrapped. very long lines are wrapped. very long lines are wrapped. very long lines are wrapped.
existing wrapping will be preserved if within width. existing
wrapping is preserved. existing wrapping will be preserved.
existing wrapping is preserved. existing wrapping will be
preserved. existing wrapping is preserved. existing wrapping
will be preserved. existing wrapping is preserved unless it goes too long for the display width.
""",
formatter_class=formatter,
)
parser.add_argument(
"--option",
choices=[
"red",
"blue",
],
help="""
Lots of text describing different choices.
red: a warning colour
text on the next line
blue: a longer blah blah keeps going going going going going going going going going going
""",
)
print("\n\nDemo for {}\n".format(formatter.__name__))
parser.print_help()
demo_formatter(DescriptionWrappedNewlineFormatter)
demo_formatter(WrappedNewlineFormatter)
WrappedNewlineFormatter的演示输出
usage: arg.py [-h] [--option {red,blue}]
A program that does things.
Lots of description that describes how the program works.
very long lines are wrapped. very long lines are wrapped. very long lines are
wrapped. very long lines are wrapped. very long lines are wrapped. very long
lines are wrapped.
existing wrapping will be preserved if within width. existing
wrapping is preserved. existing wrapping will be preserved.
existing wrapping is preserved. existing wrapping will be
preserved. existing wrapping is preserved. existing wrapping
will be preserved. existing wrapping is preserved unless it goes too long for
the display width.
optional arguments:
-h, --help show this help message and exit
--option {red,blue} Lots of text describing different choices.
red: a warning colour
text on the next line
blue: a longer blah blah keeps going going going
going going going going going going going
DescriptionWrappedNewlineFormatter的演示输出
usage: arg.py [-h] [--option {red,blue}]
A program that does things.
Lots of description that describes how the program works.
very long lines are wrapped. very long lines are wrapped. very long lines are
wrapped. very long lines are wrapped. very long lines are wrapped. very long
lines are wrapped.
existing wrapping will be preserved if within width. existing
wrapping is preserved. existing wrapping will be preserved.
existing wrapping is preserved. existing wrapping will be
preserved. existing wrapping is preserved. existing wrapping
will be preserved. existing wrapping is preserved unless it goes too long for
the display width.
optional arguments:
-h, --help show this help message and exit
--option {red,blue} Lots of text describing different choices. red: a
warning colour text on the next line blue: a longer
blah blah keeps going going going going going going
going going going going
```
我想在描述文本中有手动换行符,并自动换行;但是这里没有一个建议对我有用-所以我最终修改了答案中给出的SmartFormatter类;尽管argparse方法名不是一个公共API,但这是我拥有的(作为一个名为test.py的文件):
import argparse
from argparse import RawDescriptionHelpFormatter
# call with: python test.py -h
class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
#def _split_lines(self, text, width): # RawTextHelpFormatter, although function name might change depending on Python
def _fill_text(self, text, width, indent): # RawDescriptionHelpFormatter, although function name might change depending on Python
#print("splot",text)
if text.startswith('R|'):
paragraphs = text[2:].splitlines()
rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
#print(rebroken)
rebrokenstr = []
for tlinearr in rebroken:
if (len(tlinearr) == 0):
rebrokenstr.append("")
else:
for tlinepiece in tlinearr:
rebrokenstr.append(tlinepiece)
#print(rebrokenstr)
return '\n'.join(rebrokenstr) #(argparse._textwrap.wrap(text[2:], width))
# this is the RawTextHelpFormatter._split_lines
#return argparse.HelpFormatter._split_lines(self, text, width)
return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)
parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah .blah blah
Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl blah bl bl a blah, bla blahb bl:
blah blahblah blah bl blah blahblah""")
options = parser.parse_args()
这是它在2.7和3.4中的工作原理:
$ python test.py -h
usage: test.py [-h]
Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah
.blah blah
Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl
blah bl bl a blah, bla blahb bl:
blah blahblah blah bl blah blahblah
optional arguments:
-h, --help show this help message and exit
另一种简单的方法是包含文本包。
例如,
import argparse, textwrap
parser = argparse.ArgumentParser(description='some information',
usage='use "python %(prog)s --help" for more information',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--argument', default=somedefault, type=sometype,
help= textwrap.dedent('''\
First line
Second line
More lines ... '''))
通过这种方式,我们可以避免在每个输出行前面有很长的空白。
usage: use "python your_python_program.py --help" for more information
Prepare input file
optional arguments:
-h, --help show this help message and exit
--argument ARGUMENT
First line
Second line
More lines ...