Options with Options with Python argparse?

青春壹個敷衍的年華 提交于 2019-12-08 01:41:05

问题


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:


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.



来源:https://stackoverflow.com/questions/17537465/options-with-options-with-python-argparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!