2011-09-13 49 views
3

我試圖爲執行我的Python腳本:解析Python中的命令行參數:得到一個KeyError異常

python series.py supernatural 4 6 
 
Supernatural : TV Series name 
4 : season number 
6 : episode number 

現在,在我的劇本我使用上述三個參數,以獲取事件的標題:

import tvrage.api 
import sys 

a = sys.argv[1] 
b = sys.argv[2] 
c = sys.argv[3] 

temp = tvrage.api.Show(a) 
name = temp.season(b).episode(c) # Line:19 
print (name.title) 

但我收到此錯誤:

File "series.py", line 19, in <module>: 
    name = super.season(b).episode(c) 
File "C:\Python26\Lib\site-packages\tvrage\api.py", line 212, in season 
    return self.episodes[n] KeyError: '4' 

我正在使用Python 2.6。

+0

你能告訴我們錯誤嗎? – birryree

+0

實際上錯誤是指向我使用的API,但如果你想錯誤是'File「series.py」,第19行,在 name = super.season(b).episode(c) 文件「C:\ Python26 \ Lib \ site-packages \ tvrage \ api.py「,第212行,在季節中 return self.episodes [n] KeyError:'4' – RanRag

回答

3

Python TVRage API期待整數,而不是字符串(這是你從argv得到什麼):

name = temp.season(int(b)).episode(int(c)) 

會糾正錯誤,如果第4季第6集存在。

您應該看看Python附帶的命令行解析模塊。對於3.2/2.7或更高版本,請使用argparse。對於舊版本,請使用optparse。如果您已經知道C的getopt,請使用getopt

3

A KeyError表示您試圖訪問不存在的字典中的項目。此代碼將產生錯誤,因爲沒有'three'關鍵在詞典:

>>> d = dict(one=1, two=2) 
>>> d 
{'two': 2, 'one': 1} 
>>> d['three'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 'three' 

the Python Wiki entry on KeyErrors

+0

這是'KeyError'的精美描述,但沒有回答這個問題 - 它沒有告訴他爲什麼字典中不存在該鍵。 – agf