如何将 python argparse 与条件可选参数一起使用?

How to use python argparse with conditionally optional arguments?

这是当前代码。

import time
import collections
from modules import outputs
from modules import scrub
from modules import lookups

parser = argparse.ArgumentParser(description='AppMap Converter to Generate Asset Files from AppMapp Data')
parser.add_argument("operation", nargs='?', default="empty", help='The operation to perform')
parser.add_argument("input", nargs='?', default="empty", help='The input AppMapp File Path')
parser.add_argument("output", nargs='?', default="empty", help='The output Asset File Path')
args = parser.parse_args()

start = time.time()

if(args.operation == "Convert"):
    input_file_path = args.input
    output_file_path = args.output
    #DO LOTS OF STUFF
else:
    exit()

这个脚本叫做 sacsproc,所以我 运行 它从命令行如下:

./sacsproc Convert input.csv output.csv

一切正常,问题是我需要更多 sacsproc 命令,这些命令可能具有完全不同的辅助参数集。即一个命令可能是:

./sacsproc Clean -rts input.csv output.csv err.csv

因此,我试图确定如何定义以第一个参数为条件的参数?在我看来,我正在考虑执行我正在尝试执行的操作的 zfs 命令行实用程序(例如 zpool create mirror sdb sdc 与 zpool remove sda)。

使用子解析器

subparsers = parser.add_subparsers(help="sub-command help")

group1 = subparsers.add_parser("something",help="do something")
group1.set_defaults(which="g1") # some default value (so you know which group was activated)
group1.add_argument("ARG",help='do something on ARG')

group2 = subparsers.add_parser("other",help="do something else")
group2.set_defaults(which="g2") # give some default value
group2.add_argument("ARG",help='do something else on ARG')

好的...

import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="sub-command help")
g1 = subparsers.add_parser("thing1",help="bind to a port and just echo back anything it gets ... with a prompt")
g1.set_defaults(which="g1")
g1.add_argument("input",help='the input file')
g1.add_argument("output",help='the output file')
g2 = subparsers.add_parser("thing2",help="create a bridge between two ports, this is useful for generating a logfile")
g2.set_defaults(which="g2")
g2.add_argument("input",help='thie input file')
g2.add_argument("output",help='the output file')
g2.add_argument("error",help="the err file")


def print_help(args):
    print "ARGS:",args
    try:
        parser.parse_args(args)
    except:
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"

print_help(["-h"])
print_help(["thing1","-h"])
print_help(["thing2","-h"])