带依赖的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 个回答
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)
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()