Options with Options with Python argparse?

2019-05-19 17:01发布

I'm writing a script in Python, and using argparse to parse my arguments. The script is supposed to compare two different "aligners" from a pool of available aligners, and each aligner has some configuration options.

I want to be able to call my script with something like:

./script.py --aligner aligner1 --param 12 --aligner aligner2 --param 30 --other_param 28

I want to get out of this some sort of structure where the first --param option "belongs" to the first --aligner option, and the second --param and the --other_param options "belong" to the second --aligner option.

Is argparse capable of this sort of structured option parsing?

If so, what is the best way to do it? If not, is there another library I should look at?

Is there a drastically better UI design that I could be using instead of this?

1条回答
戒情不戒烟
2楼-- · 2019-05-19 17:40

In general, I think what you want is impossible because you cannot associate the optional parameter values together. That is, I can't see how to associate --param 12 with --aligner aligner1.

However.

You can use argparse as follows:

p = argparse.ArgumentParser ()
p.add_argument ("--aligner", action="append", nargs="+")

This will create multiple aligner arguments, each requiring at least one argument (the aligner name). You then can use an additional encoding scheme (that you can document in the help text for the parser) which encodes the parameters for each aligner. For example, you could call your script with:

./script.py --aligner aligner1 param=12 --aligner aligner2 param=30 other_param=28

You then split out the additional arguments for each aligner into a list, split by '=' and then create a dict. Potentially updating with a default set of arguments.

查看更多
登录 后发表回答