当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to specify multiple instances of same type of parent parser in argparse

问题描述:

Some apps I am converting from Perl to Python have quite a clever system of argument parsing where command options with specified leading substrings ("prefixes"), such as '-xyz-..' are identified and handled as part of standard sets. So this seems a good fit for the Python "parents" facility of argparse.

However, the Perl code also allows multiple instances of the same type of standard set, and it isn't obvious if or how this argparse parent facility can be extended to deal with that.

So what I need is something like:

from xyz import parser # instance 1 (options start -xyz1-..)

from xyz import parser # instance 2 (options start -xyz2-..)

parser = argparse.ArgumentParser(parents=[xyz1.parser, xyz2.parser])

...

So in this rough code outline need some way to

  1. Indicate each instance of the same class uniquely, and
  2. indicate within each class the unique prefix of the options it is supposed to deal with.

网友答案:

This seems to do what you want.

main.py:

import argparse
import xyz1
import xyz2

parser = argparse.ArgumentParser(
    description="My program",
    parents=[xyz1.parser, xyz2.parser])
parser.add_argument("-s", "--sky")
parser.parse_args(["--help"])

xyz1.py

import argparse

parser = argparse.ArgumentParser(description="XYZ1 args", add_help=False)
parser.add_argument("-xyz1-cat", action='store_true')
parser.add_argument("-xyz1-dog", action='store_true')

xyz2.py

import argparse

parser = argparse.ArgumentParser(description="XYZ2 args", add_help=False)
parser.add_argument("-xyz2-lizard", action='store_true')
parser.add_argument("-xyz2-spock", action='store_true')

Result:

$ python main.py 
usage: main.py [-h] [-xyz1-cat] [-xyz1-dog] [-xyz2-lizard] [-xyz2-spock]
               [-s SKY]

My program

optional arguments:
  -h, --help         show this help message and exit
  -xyz1-cat
  -xyz1-dog
  -xyz2-lizard
  -xyz2-spock
  -s SKY, --sky SKY

Edit

Based on OP's comment, "I would like just one xyz.py module that can be parametrized", this might be what he wants:

main.py

import argparse
import xyz

parser = argparse.ArgumentParser(
    description="My program",
    parents=[xyz.parser("xyz1"), xyz.parser("xyz2")])
parser.add_argument("-s", "--sky")
parser.parse_args(["--help"])

xyz.py

import argparse

def parser(prefix):
    result = argparse.ArgumentParser(add_help=False)
    result.add_argument("--%s-cat"%prefix, action='store_true')
    result.add_argument("--%s-dog"%prefix, action='store_true')
    return result
分享给朋友:
您可能感兴趣的文章:
随机阅读: