带有 Python argparse 选项的选项? [英] Options with Options with Python argparse?

查看:35
本文介绍了带有 Python argparse 选项的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 编写脚本,并使用 argparse 来解析我的参数.该脚本应该从可用对齐器池中比较两个不同的对齐器",每个对齐器都有一些配置选项.

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

我想摆脱这种结构,其中第一个 --param 选项属于"第一个 --aligner 选项,第二个 --param 和 --other_param 选项属于"第二个--aligner 选项.

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.

argparse 是否能够进行这种结构化选项解析?

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?

有没有比这个更好的 UI 设计?

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

推荐答案

总的来说,我认为你想要的是不可能的,因为你不能将可选参数值关联在一起.也就是说,我看不到如何将 --param 12--aligner aligner1 关联起来.

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.

不过.

您可以使用 argparse 如下:

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

然后您将每个对齐器的附加参数拆分为一个 list,由 '=' 拆分,然后创建一个 dict.可能使用一组默认参数进行更新.

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.

这篇关于带有 Python argparse 选项的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆