2014-02-10 34 views
0

我正在嘗試使用getopts進行命令行解析。但是,如果我通過:=將選項設置爲具有強制參數,並且在命令行中未給出參數,則以下選項將作爲第一個選項的參數。我想這反而會產生一個錯誤。這怎麼解決?Python getopt採取第二個選項作爲第一個選項的參數

工作例如:

#!/usr/bin/env python 

import sys, getopt, warnings 


argv = sys.argv 

try: 
    opts, args = getopt.getopt(argv[1:], "c:", ["config-file=", "sample-list="]) 
    print >> sys.stderr, opts 

except getopt.GetoptError as msg: 
    print msg 

運行這樣的命令行上運行此腳本:

python getopt_test.py --config-file --sample-list 

結果如下輸出(opts):

[('--config-file', '--sample-list')] 
+2

使用[argparse](http://docs.python.org/2.7/library/argparse.html)代替getopt,如[getopt]文檔中所述(http://docs.python.org/ 2.7/library/getopt.html):*不熟悉C getopt()函數的用戶,或者希望編寫更少的代碼並獲得更好的幫助和錯誤消息的用戶應該考慮使用argparse模塊。 – zmo

回答

0

沒有什麼運行時出錯:

python getopt_test.py --config-file --sample-list 

在你的代碼片段:

opts, args = getopt.getopt(argv[1:], "c:", ["config-file=", "sample-list="]) 

# config-file requires argument i.e what ever argument come next in sys.argv list 
# sample-list requires argument i.e what ever argument come next in sys.argv list 

所以,當你運行爲python getopt_test.py --config-file --sample-list

--sample列表只是一個參數--config文件

讓我們通過打印opts進行確認,它是包含元組內第一個元素作爲選項名稱,第二個元素作爲參數的元組元素列表。

tmp/: python get.py --config-file --sample-list 
[('--config-file', '--sample-list')] [] 
tmp/: 

# lets put a proper argument for config-file 
tmp/: python get.py --config-file 'argument_for_config_file' 
[('--config-file', 'argument_for_config_file')] [] 
tmp/: 

# Lets run with proper sample-list 
tmp/: python get.py --config-file 'argument_for_config_file' --sample-list 'here is the 
list' 
[('--config-file', 'argument_for_config_file'), ('--sample-list', 'here is the list')] 
[] 
tmp/: 

因此,您需要編寫自己的正確解析以確保用戶提供正確的選項和參數。如果您使用optparse。

關於異常:異常getopt.GetoptError

時無法識別的選項參數列表或當需要參數的選項 給出未找到此升高。但在你的情況下,沒有任何規則是違反的,這就是爲什麼它沒有任何錯誤地默默運行。

爲了防止這一切optparse陷阱:強烈建議使用argparse這有很多新的和良好的功能來解決所有的問題。

+0

因此,沒有辦法讓getopt認識到以「 - 」開頭的東西不應該是一個選項的參數,因此,由於沒有提供參數而引發錯誤? – MarlinaH

+0

如果您想了解更多詳細信息getopt解析sys.argv,請點擊http://hg.python.org/cpython/file/2.7/Lib/getopt.py#l144 –

相關問題