1

我正在构建一个具有多个子解析器的软件,我想要那些具有不同convert_arg_line_to_args定义的软件,所以我所做的是考虑到选择的子解析器来替换我的解析器的功能:

parser = ArgumentParser(fromfile_prefix_chars='@')
subparsers = parser.add_subparsers(title='Available sub commands')

sub_parser = subparsers.add_parser("sub1", help="sub1")
sub_parser.add_argument("--paramsub1", required=True, dest="paramsub1")
sub_parser.set_defaults(cmd_object="sub1")

sub_parser = subparsers.add_parser("sub2", help="sub2")
sub_parser.add_argument("--paramsub2", required=True, dest="paramsub2")
sub_parser.set_defaults(cmd_object="sub2")

我希望 argparse 不检查参数,但告诉我选择了哪个子解析器:

args = vars(parser.parse_args())
if args["cmd_object"] == "sub1": parser.convert_arg_line_to_args = function1
elif args["cmd_object"] == "sub2": parser.convert_arg_line_to_args = function2
args = vars(parser.parse_args())

有任何想法吗?

4

1 回答 1

1

Do you want to check the subparser name just so you can set the convert_arg_line_to_args function? You could, instead, change that function during setup.

How about this setup?

def function1(arg_line):
    print('function1: %r'%arg_line)
    return [arg_line]

def function2(arg_line):
    print('function2: %r'%arg_line)
    return arg_line.split()

parser = ArgumentParser()
subparsers = parser.add_subparsers(title='Available sub commands', dest='cmd_object')

sub_parser1 = subparsers.add_parser("sub1", help="sub1",fromfile_prefix_chars='@')
sub_parser1.convert_arg_line_to_args = function1
sub_parser1.add_argument("--paramsub1")

sub_parser2 = subparsers.add_parser("sub2", help="sub2",fromfile_prefix_chars='@')
sub_parser2.convert_arg_line_to_args = function2
sub_parser2.add_argument("--paramsub2")

I moved fromfile_prefix_chars='@' from the parser to the subparsers. That way the parser does not try to read the argument files.

Usually required arguments are defined as positional (without the --).

Using dest='cmd_object' puts the subparser name into the namespace. sest_defaults also works, but is more useful when you want to set that value to a function (or other non-string).

于 2013-08-14T17:15:48.777 回答