最大限度地减少 Python 脚本参数的代码重复(使用“argparse”或其他模块)
假设有多个脚本:script_1.py
、script_2.py
、script_3.py
、script_4.py
、script_5.py
、script_6.py
等,目标是最大限度地减少脚本作为输入的参数的代码重复。
作为场景示例:
script_1.py
、script_2.py
、script_3.py
有几个共同的参数 =>可能的解决方案:可以利用argparse的parent_parserscript_4.py
、script_5.py
、script_6.py
有几个共同的参数=>可能的解决方案:可以利用argparse的parent_parserscript_5.py
script_6.py
script_7.py
script_8.py
有一个共同点 =>可能的解决方案:将 args 放入字典中(下面的片段示例)
"""
python run_app_w_argparse_example.py --arg_1 1
"""
import argparse
from typing import Dict
APPS_ARGS = {"--arg_1": dict(help="arg_1 description", type=int),
"--arg_2": dict(help="arg_2 description", type=str, default="hi")}
def parser_example() -> Dict:
parser = argparse.ArgumentParser(description="Description")
parser.add_argument("--arg_1", **APPS_ARGS["--arg_1"])
return vars(parser.parse_args())
if __name__ == '__main__':
print(parser_example())
一个不方便的地方是“--arg1”在 add_argument 中重复两次。有办法避免这种情况吗?总体上有更好的解决方案吗?
Let's say one has several scripts: script_1.py
, script_2.py
, script_3.py
, script_4.py
, script_5.py
, script_6.py
, etc and the objective is to minimize code repetition in terms of arguments the scripts take as input.
As an example of scenarios:
script_1.py
,script_2.py
,script_3.py
have several arguments in common => possible solution: one can leverage parent_parser of argparsescript_4.py
,script_5.py
,script_6.py
have several arguments in common => possible solution: one can leverage parent_parser of argparsescript_5.py
script_6.py
script_7.py
script_8.py
have one argument in common => possible solution: put the args in a dictionary (snippet example below)
"""
python run_app_w_argparse_example.py --arg_1 1
"""
import argparse
from typing import Dict
APPS_ARGS = {"--arg_1": dict(help="arg_1 description", type=int),
"--arg_2": dict(help="arg_2 description", type=str, default="hi")}
def parser_example() -> Dict:
parser = argparse.ArgumentParser(description="Description")
parser.add_argument("--arg_1", **APPS_ARGS["--arg_1"])
return vars(parser.parse_args())
if __name__ == '__main__':
print(parser_example())
One inconvenient is that "--arg1" gets repeated twice in add_argument. Is there a way to avoid that? Is there a better solution overall?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我在使用子命令或有许多共享相同基本参数的脚本时偶尔用于 python 工具的模式。
简而言之,我创建了一个嵌套结构(我承认看起来有点可怕),它允许动态创建解析器。
基本布局是:
每个内部元组都包含 CLI 标志和参数选项的字典。
字典必须是最后一个元素。
这样做的原因是因为元组可以相互附加,因此参数可以堆叠起来。
This is a pattern that I occasionally use for python tools when using sub-commands or there are many scripts that share the same base args.
In short I create a nested structure (that I admit looks a bit horrible) that allows the parser to be dynamically created.
The basic layout is:
Each inner
tuple
contains the CLI flags and adict
of the argument options.the dict must be the final element.
The reason for doing it this way is because tuples can be appended to one another so arguments can be stacked up.