带有依赖项的python argparse [英] python argparse with dependencies

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

问题描述

我正在编写一个脚本,该脚本具有两个互斥的参数,以及一个仅对其中一个参数有意义的选项.我试图将argparse设置为失败,如果您使用没有意义的参数调用它的话.

I'm writing a script which has 2 arguments which are mutually exclusive, and an option that only makes sense with one of those arguments. I'm trying to set up argparse to fail if you call it with the argument that makes no sense.

要清楚:

-m -f有意义

-s有意义

-s -f应该抛出错误

没有参数很好.

我的代码是:

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
mysql_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

哪一个不起作用,因为它吐出了

Which doesn't work, as it spits out

 usage: whichboom [-h] [-s] [-m] [-f] host

而不是我所期望的:

 usage: whichboom [-h] [-s | [-h] [-s]] host

或类似的东西.

 whichboom -s -f -m 116

也不会抛出任何错误.

推荐答案

您只需要混合参数组即可.在您的代码中,您仅将一个选项分配给互斥组.我想您想要的是:

You just have the argument groups mixed up. In your code, you only assign one option to the mutually exclusive group. I think what you want is:

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
main_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

您可以跳过整个互斥的组内容并添加如下内容:

You could just skip the whole mutually exclusive group thing and add something like this:

usage = 'whichboom [-h] [-s | [-h] [-s]] host'
parser = argparse.ArgumentParser(description, usage)
options, args = parser.parse_args()
if options.ssh and options.firefox:
    parser.print_help()
    sys.exit()

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

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