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

标签 python python-2.7 python-3.x command-line-arguments argparse

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

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/

相关文章:

sql-server - 在 Azure Databricks 中使用 Python 将 DF 写入 SQL Server

python - __name__ 的目的是什么?

python - Flask 蓝图中的 render_template 使用其他蓝图的模板

python - 每次访问相关模型时 Django 都会重新查询吗?

python - tkinter 中的循环按钮和功能分配

linux - python : Should I use shutil or subprocess to manipulate files and directories as a better approach?

python - 多次尝试除非值可能不存在

python - Python 中的身份集?

python - urllib.request.urlopen 不接受带空格的查询字符串

python - Airflow 中 Python Operator 中 execution_timeout 的默认值