我有一个带有3-4个参数的解析器,它运行良好。我想向脚本提供未知数量的额外参数,这些参数将被加载到模板中。我已经阅读了argparse文档,但我不确定是否可能。我可以使用
就我个人而言,我的建议如下:
parse_known_arguments()
,但我仍然必须自己处理["--placeholder1", "value1", "--placeholder2", "value2", ...]
数组。我应该继续进行,还是有更pythonic的方法?就我个人而言,我的建议如下:
parser = argparse.ArgumentParser()
parser.add_argument("--template", required=True)
parser.add_argument("--location", required=True)
args,unknown = parser.parse_known_arguments()
tpl = LoadTemplate(args.template)
# Missing part where I transform unknown into an dict or namespace called extraarguments
raw = tpl.render(extraarguments)
# Print into args.location raw
render.py --template template1 --location /path/to/invoices --author John --customer Customer1 --title "Your invoice is ready!"
render.py --template template2 --location /path/to/newsletter --customer Customer2 --sender john@store.com --subject "Weekly newsletter"
在这两种情况下,template
和location
都必须存在,但是额外的参数应该被解包并发送到模板渲染函数中。看起来好像只需要一行代码,但是是否有更多Pythonic的方法呢?
argparse
可以解析的命令参数的例子吗? - Vivian De Smedtdocopt
,它会让你微笑。 - bgusach