在编写脚本时,我有时会使用一个函数来封装脚本的确切内容。这是因为我可能想从代码中调用该函数或将其作为脚本运行。有没有办法避免重复argparse中帮助字符串中的函数参数的文档?例如:
import argparse
def my_function(arg_one, arg_two):
"""
arg_one: The first argument.
arg_two: The second argument.
"""
print("The first argument is %r" % arg_one)
print("The second argument is %r" % arg_two)
if __name__=="main":
parser = argparse.ArgumentParser()
parser.add_argument('--arg-one', help="The first argument.")
parser.add_argument('--arg-two', help="The second argument.")
args = parser.parse_args()
my_function(args.arg_one, args.arg_two)
由于函数和脚本的参数完全一致,你可以看到我必须两次记录它们(“第一个参数”,“第二个参数”)。这是一个微不足道的问题,但它真的很烦人。我应该根本不使用功能吗?
这是我写它的方式......
""" My Crazy Program
Usage:
my_prog [options]
Options:
"""
def my_function(file_output, file_input, recursive=False):
"""
output=str: specifies an output path
input=str: specifies an input path
recursive: apply recursively
"""
print("The first argument is %r" % file_output)
print("The second argument is %r" % file_input)
print("The third argument is %r" % recursive)
# This is where the magic happens
__doc__ += '\n'.join(f' --{parsed[0]: <15} {parsed[1]}'
for parsed in (
line.strip().split(': ')
for line in my_function.__doc__.split('\n'))
if len(parsed) == 2)
if __name__ == "__main__":
from docopt import docopt
ARGS = docopt(__doc__)
my_function(ARGS['--output'], ARGS['--input'], ARGS['--recursive'])
好的,你看到了神奇的线条(从__doc__ += ...
开始),它使模块的文档成为:
My Crazy Program
Usage:
my_prog [options]
Options:
--output=str specifies an output path
--input=str specifies an input path
--recursive apply recursively
然后,docopt解析并返回此字典:
$ python my_prog
{'--input': None,
'--output': None,
'--recursive': False}
$ python my_prog --output /dev/null --recursive
{'--input': None,
'--output': '/dev/null',
'--recursive': True}
哪个可用于调用函数并获得结果:
The first argument is '/dev/null'
The second argument is None
The third argument is True
我喜欢这个解决方案,因为它是单行,但我同意你的说法并不漂亮,我会让你自己编写一个漂亮的功能,为每个文件自动执行:o)