我正在写一个脚本,它有两个相互排斥的参数,还有一个只有一个参数才有意义的选项。我正在尝试将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也不会抛出任何错误。
发布于 2010-12-17 07:09:22
你只是把参数组搞混了。在您的代码中,您只能将一个选项分配给互斥的组。我想你想要的是:
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()发布于 2010-12-17 07:04:30
在创建解析器时添加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)https://stackoverflow.com/questions/4466197
复制相似问题