带有依赖关系的python argparse

时间:2010-12-16 22:57:33

标签: python argparse

我正在编写一个脚本,它有两个相互排斥的参数,以及一个只对其中一个参数有意义的选项。我试图将argparse设置为失败,如果你用没有意义的参数调用它。

要明确:

-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')

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

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

而不是我期望的那样:

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

或某些。

 whichboom -s -f -m 116

也不会抛出任何错误。

2 个答案:

答案 0 :(得分:8)

你只是让参数组混淆了。在您的代码中,您只为互斥组分配一个选项。我想你想要的是:

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')

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

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()

答案 1 :(得分:2)

创建解析器时添加usage参数:

usage = "usage: whichboom [-h] [-s | [-h] [-s]] host"
description = "Lookup servers by ip address from host file"
parser = argparse.ArgumentParser(description=description, usage=usage)

来源:http://docs.python.org/dev/library/argparse.html#usage

相关问题