gpt4 book ai didi

Python argparse 解析无法识别的参数

转载 作者:行者123 更新时间:2023-11-28 21:15:29 27 4
gpt4 key购买 nike

我有一个带有 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"

在这两种情况下,templatelocation 都必须存在,但额外的参数应该被解压并发送到模板渲染函数中。它看起来像一条直线,但是否有更 Pythonic 的方式来做到这一点?

最佳答案

假设 unknown 列表是键和值的交替列表,它可以变成一个字典:

adict = dict(zip(unknown[:-1:2],unknown[1::2]))

zip 部分将列表转换成对列表,然后将其转换为字典。您可能需要对值进行更多处理,以从键中删除“--”前缀。如果您需要检查错误,例如不匹配的“键值”序列,您可能需要更明确的迭代。

这是一个完整保留“--”的版本:

templates = {'template1': "from: {--author} to: {--customer} re: {--title}",
'template2': "from: {--sender} to: {--customer} re: {--subject}"}

def parser():
parser = argparse.ArgumentParser()
parser.add_argument("--template", required=True, choices=templates)
parser.add_argument("--location", required=True)
args,unknown = parser.parse_known_args()
extraarguments = dict(zip(unknown[::2], unknown[1::2]))
tpl = templates[args.template]
raw = tpl.format(**extraarguments)
return raw
print parser()

用你的 2 个样本产生:

In [25]: run stack30139426.py --template template1 --location /path/to/invoices --author John --customer Customer1 --title "Your invoice is ready!"
from: John to: Customer1 re: Your invoice is ready!

In [26]: run stack30139426.py --template template2 --location /path/to/newsletter --customer Customer2 --sender john@store.com --subject "Weekly newsletter"
from: john@store.com to: Customer2 re: Weekly newsletter

还有关于输入字典或其他未知键/值对的其他 SO 问题。

一个建议是使用 key:value 语法,然后使用简单的 [kv.split(':') for kv in unknowns] 来生成一个对列表:

run stack30139426.py --template template2 --location /path/to/newsletter customer:Customer2 sender:john@store.com subject:"Weekly newsletter"

另一种是使用JSON语法

run stack30139426.py --template template2 --location /path/to/newsletter '{"customer":"Customer2", "sender":"john@store.com", "subject":"Weekly newsletter"}'

关于Python argparse 解析无法识别的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com