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

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

问题描述

我正在编写一个脚本,它有 2 个相互排斥的参数,以及一个仅对其中一个参数有意义的选项.如果您使用毫无意义的参数调用它,我正在尝试将 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天全站免登陆