我正在编写一个脚本,其中有两个参数是互斥的,一个选项只对其中一个参数有意义。我试图将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
也不会抛出任何错误。
你只是把辩论小组搞混了。在代码中,只为互斥组分配一个选项。我想你想要的是:
你可以跳过整个相互排斥的组,然后添加如下内容:
创建解析器时添加
usage
参数:来源:http://docs.python.org/dev/library/argparse.html#usage
相关问题 更多 >
编程相关推荐