在由多个自定义模块支持的多个脚本中使用 python 的 argparse [英] Using python's argparse in multiple scripts backed by multiple custom modules
问题描述
我正在构建一组脚本和模块来管理我们的基础设施.为了使事情井井有条,我想尽可能多地整合工作,并尽量减少新脚本的样板.
I'm building out a set of scripts and modules for managing our infrastructure. To keep things organized I'd like to consolidate as much effort as possible and minimize boiler plate for newer scripts.
特别是这里的问题是整合 ArgumentParser 模块.
In particular the issue here is to consolidate the ArgumentParser module.
一个示例结构是让脚本和库像这样组织:
An example structure is to have scripts and libraries organized something like this:
|-- bin
|-- script1
|-- script2
|-- lib
|-- logger
|-- lib1
|-- lib2
在这种情况下,script1
可能只使用 logger
和 lib1
,而 script2
将使用logger
和 lib2
.在这两种情况下,我都希望记录器接受-v"和-d",而 script1
也可以接受其他参数和 lib2
其他参数.我知道这可能会导致冲突,并将手动管理.
In this scenario script1
may only make use of logger
and lib1
, while script2
would make use of logger
and lib2
. In both cases I want the logger to accept '-v' and '-d', while script1
may also accept additional args and lib2
other args. I'm aware this can lead to collisions and will manage that manually.
script1
#!/usr/bin/env python
import logger
import lib1
argp = argparse.ArgumentParser("logger", parent=[logger.argp])
script2
#!/usr/bin/env python
import logger
import lib2
记录器
#!/usr/bin/env python
import argparse
argp = argparse.ArgumentParser("logger")
argp.add_argument('-v', '--verbose', action="store_true", help="Verbose output")
argp.add_argument('-d', '--debug', action="store_true", help="Debug output. Assumes verbose output.")
每个脚本和库都可能有自己的参数,但是这些都必须合并到一个最终的 arg_parse() 中
Each script and lib could potentially have it's own arguments, however these would all have to be consolidated into one final arg_parse()
到目前为止,我的尝试导致无法继承/扩展 argp 设置.如何在库文件和脚本之间完成此操作?
My attempts so far have resulted in failing to inherit/extend the argp setup. How can this be done in between a library file and the script?
推荐答案
最简单的方法是在每个模块中有一个方法,该方法接受一个 ArgumentParser
实例并向其添加自己的参数.
The simplest way would be by having a method in each module that accepts an ArgumentParser
instance and adds its own arguments to it.
# logger.py
def add_arguments(parser):
parser.add_argument('-v', '--verbose', action="store_true", help="Verbose output")
# ...
# lib1.py
def add_arguments(parser):
parser.add_argument('-x', '--xtreme', action="store_true", help="Extremify")
# ...
每个脚本都会创建自己的ArgumentParser
,将其传递给提供参数的每个模块,然后添加自己的特定参数.
Each script would create their ArgumentParser
, pass it in to each module that provides arguments, and then add its own specific arguments.
# script1.py
import argparse, logger, lib1
parser = argparse.ArgumentParser("script1")
logger.add_arguments(parser)
lib1.add_arguments(parser)
# add own args...
这篇关于在由多个自定义模块支持的多个脚本中使用 python 的 argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!