带有依赖关系的python argparse

ric*_*cho 12 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')
Run Code Online (Sandbox Code Playgroud)

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

 usage: whichboom [-h] [-s] [-m] [-f] host
Run Code Online (Sandbox Code Playgroud)

而不是我期望的:

 usage: whichboom [-h] [-s | [-h] [-s]] host
Run Code Online (Sandbox Code Playgroud)

或者某些.

 whichboom -s -f -m 116
Run Code Online (Sandbox Code Playgroud)

也不会抛出任何错误.

use*_*424 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')
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)