2010-12-16 64 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