Using python argparse in multiple scripts supported by multiple custom modules

I create a set of scripts and modules for managing our infrastructure. In order to maintain organization, I would like to combine as many efforts as possible and minimize the boiler plate for new scenarios.

In particular, the problem is the consolidation of the ArgumentParser module.

An example structure is for scripts and libraries to organize something like this:

|-- bin
    |-- script1
    |-- script2
|-- lib
    |-- logger
    |-- lib1
    |-- lib2

In this scenario script1, only loggerand can be used lib1, and script2will use loggerand lib2. In both cases, I want the logger to accept "-v" and "-d", and script1also be able to accept additional arguments and lib2other arguments. I know that this can lead to collisions and will manage it 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

Registrar

#!/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.")

Each script and lib can potentially have their own arguments, however they should all be combined into one final arg_parse ()

My attempts so far have led to failing to inherit / extend the argp setting. How can this be done between a library file and a script?

+5
source share
1 answer

, ArgumentParser .

# 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")
    # ...

script ArgumentParser, , , .

# script1.py
import argparse, logger, lib1
parser = argparse.ArgumentParser("script1")
logger.add_arguments(parser)
lib1.add_arguments(parser)
# add own args...
+6

All Articles