2013-08-20 23 views
12

我試着學習如何argparse.ArgumentParser作品,我已經寫了這幾行:使用Python argparse.ArgumentParser方法

global firstProduct 
global secondProduct 
myparser=argparse.ArgumentParser(description='parser test') 
myparser.add_argument("product1",help="enter product1",dest='product_1') 
myparser.add_argument("product2",help="enter product2",dest='product_2') 

args=myparser.parse_args() 

firstProduct=args.product_1 
secondProduct=args.product_2 

我只是想,當用戶運行此腳本有兩個參數的我代碼分別將它們分配給firstProductsecondProduct。但它不起作用。有沒有人告訴我爲什麼?在此先感謝

+2

你應該描述錯誤,而不只是說'它不工作'。錯誤消息:「ValueError:dest爲位置參數提供兩次」非常重要。 unutbu的回答解決了這個問題。 – hpaulj

回答

11

使用位置參數時忽略dest參數。對於位置參數提供的名稱將是參數的名稱:

import argparse 
myparser = argparse.ArgumentParser(description='parser test') 
myparser.add_argument("product_1", help="enter product1") 
myparser.add_argument("product_2", help="enter product2") 

args = myparser.parse_args() 
firstProduct = args.product_1 
secondProduct = args.product_2 
print(firstProduct, secondProduct) 

運行% test.py foo bar打印

('foo', 'bar') 
+0

非常感謝。這裏還有2個問題。 1)寫有double quates或single的product_1是否有區別? 2)位置參數和其他參數有什麼區別? – caesar

+2

'dest'參數可以與'optionals'一起使用(以'-'開頭) – hpaulj

+2

(1)如果指定單引號或雙引號的字符串,結果沒有區別。 (2)當「add_argument」的第一個參數以 「-'或」 - 「開頭時,它是一個用於引用報價的簡單引用: ''''''或''」'可選參數沒有破折號,它是位置 參數,位置參數被它們的位置識別:'test.py foo bar' 將foo解釋爲處於第一位置,因此它與第一位置參數關聯, 'product_1' – unutbu

6

除了unutbu's answer,你也可以使用metavar屬性,以使目標變量和顯示在幫助菜單中的變量名稱不同,如this link中所示。

例如,如果你這樣做:

myparser.add_argument("firstProduct", metavar = "product_1", help = "enter product1") 

您將在args.firstProduct爲您提供的說法,但有它列爲幫助product_1