gpt4 book ai didi

python - ArgumentParser.add_argument : How to use action parameter with custom type parameter?

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:24 24 4
gpt4 key购买 nike

当我尝试做关于使用的问题时:

parser.add_argument("--blah", type=func, help="Whatever", action='store_true')

...我收到此错误:

TypeError: __init__() got an unexpected keyword argument 'type'

我真正想要的是当在命令行上使用此标志时运行一个名为 func 的函数(指定为上面的参数类型),如下所示:

python3 script.py --blah

这可能吗?如果我需要更详细地回答我的问题,请告诉我。

最佳答案

type 参数是一个函数,用于测试和/或将命令行参数转换为将存储在 args 命名空间中的内容。

parser.parse_args('--foo', type=int)  # default store action

会将 ['--foo','123'] 转换为 Namespace(foo=123),而不是 foo='123'.

但是 action='store_true' 创建一个 True/False 参数。标志后不需要任何参数。所以给它一个type参数是没有意义的。诚然,错误消息可能会更清晰,但这种错误并不经常出现。这是一个开发问题,而不是运行时问题。

正如其他人所指出的,您可以在解析后使用 args.blahTrue/False 值有条件地运行您的 func

您希望什么时候运行func?解析完所有命令行后?或者当它仍在解析时?我更喜欢将解析与运行分开。使用 argparse 来找出用户想要什么;使用您自己的代码来执行之后的操作。

关于python - ArgumentParser.add_argument : How to use action parameter with custom type parameter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870225/

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