[英]Parsing command line arguments in Python: getting a KeyError
我正在嘗試執行我的Python腳本:
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。
Python TVRage API期望整數,而不是字符串(這是你從argv
得到的):
name = temp.season(int(b)).episode(int(c))
如果第4季第6集存在,將糾正錯誤。
您應該看一下Python附帶的命令行解析模塊。 對於3.2 / 2.7或更高版本,請使用argparse 。 對於舊版本,請使用optparse 。 如果您已經知道C的getopt
,請使用getopt 。
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.