带有依赖项的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()