为了避免上述解决方案的大部分“未来合规性”问题,另一种方法是装饰_format_action_invocation
代替。如果方法更改其名称当然不会中断argparse
,但至少它允许argparse
方法内的代码更新并避免代码重复。
作为奖励,以下解决方案还允许更改使用行中的帮助程序,以保持使用和调用部分之间的一致性:
import re
def deco_argparse_format_action(func, is_invoc=False):
def wrapper_format_action(*args, **kwargs):
'''
Replaces `-f FOO' or '--foo FOO` by resp. `-f=FOO` and `--foo=FOO` in argparse helper.
Although there is always possibility to use either `--foo FOO` or
`--foo=FOO`, it is sometimes better to document the '=' way
rather than the ' ' way.
For example, when the option argument contains special characters like '-'
it must be expressed with '=' in order to not confuse the shell that executes
the command line.
'''
string = func(*args, **kwargs)
if is_invoc is True:
# 'invocation section' case
patt = r"(-+[^ ,]+) +"
repl = r"\1="
else:
# 'usage section' case
patt = r"(\[-+[^ \]]+) +([^|])"
repl = r"\1=\2"
return re.sub(patt,repl,string)
return wrapper_format_action
用法:
import argparse
#-- Customize helper for options with arguments
# (print '-f=FOO, --foo=FOO' instead of '-f FOO, --foo FOO')
HelpFormatter._format_action_invocation = deco_argparse_format_action(
HelpFormatter._format_action_invocation,
is_invoc = True,
)
HelpFormatter._format_actions_usage = deco_argparse_format_action(
HelpFormatter._format_actions_usage,
)