带有依赖项的python argparse

2024-04-25 13:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,其中有两个参数是互斥的,一个选项只对其中一个参数有意义。我试图将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

也不会抛出任何错误。


Tags: tostoreaddtruehostparser参数main
2条回答

你只是把辩论小组搞混了。在代码中,只为互斥组分配一个选项。我想你想要的是:

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

创建解析器时添加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

相关问题 更多 >