2014-07-11 17 views
0

我已經爲我的python腳本定義了一些使用optparse的選項。在我的腳本中,用戶以任何順序輸入命令行參數,但我想按照預定義的方式排序。比方說,用戶輸入以下參數:按照我們預定義的方式對用戶輸入的命令行參數進行排序

scriptname -g gvalue -n nvalue -s svalue -k kvalue -e evalue 

當用戶進入以任何順序上面的參數,我想通過以下方式進行排序:

-s svalue -g gvalue -k kvalue -n nvalue -e evalue 

最後,我需要在上述順序任何時候。

+3

我不明白;無論原始順序如何,opt解析都會按名稱給出參數。 –

+1

您在optparse配置中使用與「商店操作」不同的操作? (即「回調」) –

+1

爲什麼你需要對它們進行排序?你可以對它們進行排序,但它確實不需要。另外,不推薦使用[argparse](https://docs.python.org/2/howto/argparse.html),optparse。 – sheeptest

回答

0

假設optparse被定義與諸如用於每個值的命令:

parser.add_option("-k", action="store", type="string", dest="kvalue") 

並執行爲:

(options, args) = parser.parse_args() 

然後options.kvalue將包含-k相關的用戶輸入的參數。然後,爲了序列可以產生:

(getattr(options,name) for name in ('svalue', 'gvalue', 'kvalue', 'nvalue', 'evalue')) 

另外,對原始argv字符串比較可以達到同樣的事情,而無需使用optparse

1

有可能有更好的方法來得到你想要的。你不應該這樣做。但這裏是修復:

我打算使用​​,因爲optparse已被棄用。 該代碼會顯示None如果用戶沒有指定的值,這樣的說法

## directory user$ ./argparse_ex.py -s foo -g bar -k quox -n woo -e testing123 

import argparse 
parser = argparse.ArgumentParser(description='Sorted Arguments') 
parser.add_argument('-s', help='I will be printed if the user types --help') 
parser.add_argument('-g', help='I will be printed if the user types --help') 
parser.add_argument('-k', help='I will be printed if the user types --help') 
parser.add_argument('-n', help='I will be printed if the user types --help') 
parser.add_argument('-e', help='I will be printed if the user types --help') 

args = vars(parser.parse_args()) 

sorted_args = [args['s'], args['g'], args['k'], args['n'], args['e']] 
print sorted_args 

## ['foo', 'bar', 'quox', 'woo', 'testing123'] 

argparse documentation here

相關問題