有可能有更好的方法來得到你想要的。你不應該這樣做。但這裏是修復:
我打算使用,因爲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
我不明白;無論原始順序如何,opt解析都會按名稱給出參數。 –
您在optparse配置中使用與「商店操作」不同的操作? (即「回調」) –
爲什麼你需要對它們進行排序?你可以對它們進行排序,但它確實不需要。另外,不推薦使用[argparse](https://docs.python.org/2/howto/argparse.html),optparse。 – sheeptest