tldnr:给定一个函数,有没有办法从它的签名中自动创建一个 ArgumentParser?
我有一堆函数想在命令行中公开。所以基本上,一个模块:
def copy(foo, bar, baz):
...
def move(from, to):
...
def unlink(parrot, nomore=True):
...
if __name__ == '__main__':
argparse stuff
可以像这样从命令行调用:
python commands.py move spam ham
python commands.py unlink --parrot Polly
尽管这很容易实现,但涉及很多布线:
parser = argparse.ArgumentParser(...)
subparsers = parser.add_subparsers()
...
c = subparsers.add_parser('unlink', description='Unlink a parrot')
c.add_argument('--parrot', help='parrots name', required=True)
c.add_argument('--nomore', help='this parrot is no more', action='store_true')
...
c = subparsers.add_parser('move', description='Move stuff')
...
等等,对于每个功能。最糟糕的是,如果函数参数发生变化(它们确实发生了变化),argparse 的东西需要手动同步。
如果这些函数可以为自己提供 argparse 东西会更好,这样主要代码就会像:
parser = argparse.ArgumentParser(...)
subparsers = parser.add_subparsers()
copy.register(subparsers)
move.register(subparsers)
unlink.register(subparsers)
...
我想到了这些方面的一些东西:
@args(
description='Unlink a parrot',
parrot={'required':True, 'help':'parrots name'},
nomore={'action': 'store_true', 'help': 'this parrot is no more'}
)
def unlink(parrot, nomore=True):
...
我的问题:
- 有没有这样的图书馆?
- 如果没有,是否可以编写这样的装饰器,如何编写?
- 有没有其他/更好的方法来实现我想要的?
更新:
plac似乎是解决方案。以下是如何用 plac 做我想做的事:
命令模块:cmds.py:
import plac
@plac.annotations(
foo=('the foo thing'),
bar=('the bar thing'),
fast=('do a fast copy', 'flag')
)
def copy(foo, bar, fast=False):
"""Copy some foo to bar."""
pass
@plac.annotations(
parrots=('parrots names'),
nomore=('these parrots are no more', 'flag'),
repeat=('repeat n times', 'option', 'r', int)
)
def unlink(nomore=False, repeat=1, *parrots):
"""Unlink some parrots."""
pass
#more commands...
# export commands so that plac knows about them
commands = 'copy', 'unlink'
这是主要模块:
import plac
import cmds
plac.call(cmds)
如果你问我,就很整洁。