2015-11-13 26 views
1

在下面的代碼,我試圖解析命令行參數:Python的選擇採用命令行參數屬性

import sys, getopt 
opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I') 
opts = dict(opts) 

print opts 
print args 

if '-s-' in opts: 
    print opts['-s'] 

當我運行代碼,我得到:

{} 
['python', 'Practice5.py', '-s', 'stop_list.txt', '-c', 'documents.txt', '-i', 'index.txt', '-I'] 

命令行是:

python Practice5.py -s stop_list.txt -c documents.txt -i index.txt -I 

爲什麼opts有空值?

+1

。 {'-I':'','-i':'index.txt','-c':'documents.txt','-s':'stop_list.txt'} [] – balabhi

回答

1

由於我使用Spyder,問題與命令參數。該命令必須是:

-s stop_list.txt -c documents.txt -i index.txt -I 

沒有python Practice5.py

在常規命令行,就當我跑我得到了下面的輸出命令工作正常python Practice5.py

1

測試此與實際參數獲得通過,以getopt,我得到預期的行爲:

>>> import getopt 
>>> opts, args = getopt.getopt(['-s', 'stop_list.txt', '-c', 'documents.txt', '-i', 'index.txt', '-I'], 'hs:c:i:I') 
>>> opts 
[('-s', 'stop_list.txt'), ('-c', 'documents.txt'), ('-i', 'index.txt'), ('-I', '')] 
>>> args 
[] 

the documentation

ARGS是要分析參數列表,沒有對運行程序的主要參考。

如果你也有'python'和你的腳本名稱sys.argv,你需要切從它開始更多。您也可以考慮切換到​​,如getopt文檔中的建議。

0

我建議你使用argparse;一旦你理解,它就容易得多。