2010-12-16 60 views
12

我正在写一个脚本,它有两个互斥的参数,以及一个只有其中一个参数有意义的选项。如果你用没有任何意义的论证来调用它,我试图设置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 

也不会引发任何错误。

回答

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() 
+1

这是一个功能性解决方法。我会设置它用无效的选项进行弹出,但我觉得它是一个混乱。如果今天早上我无法得到它,我会麻烦开发人员,这可能是一个错误。 – richo 2010-12-16 23:12:42

+0

我添加了mysql组和另一个选项到mutual_exclusive_group。我想我期望排除其他组的选项,但这不是它的工作原理。我结束了你的其他解决方案。 – richo 2010-12-20 06:00:40

+0

“参数组”和“互斥组”具有非常不同的目的,并且不能有意义地嵌套。 'argument_group'并不意味着'上述任何'。 – hpaulj 2017-03-31 17:09:24

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) 

来源:http://docs.python.org/dev/library/argparse.html#usage

+1

这充其量修复了命令行打印,它不别让该功能(程序接受一个无效的参数集),意味着我必须手动维护该线。使用线是我最担心的问题,我将它包括在内,主要是为了帮助某人理解发生的事情。 – richo 2010-12-16 23:09:54