简体   繁体   中英

Parsing limited switches with python argparse

Is there a way to parse only limited number of switches in a function using argparse? Say, my command is:

python sample.py -t abc -r dfg -h klm -n -p qui

And I want argparse to parse from -t to -h and leave the remaining, also show help for these only. Next I want to parse any switch after -h into another function and see corresponding help there.

Is this behavior possible in argparse? Also is there a way I can modify sys.arg it is using internally? Thanks.

python sample.py -t abc -r dfg -h klm -n -p qui

And I want argparse to parse from -t to -h and leave the remaining, also show help for these only. Next I want to parse any switch after -h into another function and see corresponding help there.

There are some issues with your specification:

Is -h the regular help? If so it has priority, producing the help without parsing the other arguments. The string after -h suggests you are treating it like a normal user define argument, which would then require initiating the parser with help turned off. But then how would you ask for help ?

What sets the break between the two parsings/help? The number of arguments, the -h flag (regardless of order), or the id of the flags. Remember argparse accepts flagged arguments in any order.

You could define one parser that knows about -t and -r , and another that handles -n and -p . Calling each with parse_known_args lets it operate without raising a unknown argument error.

You can also modify the sys.argv . parse_args (and the known variant), takes an optional argv argument. If that is none, then it uses sys.argv[1:] . So you could either modify sys.argv itself (deleting items), or you could pass a subset of sys.argv to the parser.

parser1.parse_known_args(sys.argv[1:5])
parser2.parse_known_args(['-n','one','-o','two'])
parser3.parse_args(sys.argv[3:])

Play with those ideas, and come back to us if there are further questions.

You can always modify sys.args and put anything you wish there.

As for your main question, you can have two parsers. One of them will have arguments -t to -h , the second -n and -p . Then you can use argparse 's parse_known_args() method on each parser, which will parse only the arguments defined for each of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM