在Python中解析命令行参数:获取KeyError

3
我正在尝试执行我的Python脚本,方法如下:
python series.py supernatural 4 6
超自然力量:电视剧名称
4:季数
6:集数
现在,在我的脚本中,我使用上述三个参数来获取该集的标题:
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。


实际上,错误指向我正在使用的API,但如果您想要错误,则为`File“series.py”,第19行,在<module>中: name = super.season(b).episode(c) File“C:\ Python26 \ Lib \ site-packages \ tvrage \ api.py”,第212行,在季节中 返回self.episodes [n] KeyError:'4' - RanRag
2个回答

3

Python TVRage API期望的是整数,而不是字符串(这是你从argv得到的内容):

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

若第四季第六集存在,则会纠正错误。
你应该查看Python自带的命令行解析模块。对于3.2 / 2.7或更高版本,请使用argparse。对于旧版本,请使用optparse。如果您已经了解C语言的getopt,请使用getopt

3

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'

请参阅Python Wiki KeyErrors条目.


1
这是一个关于KeyError的好描述,但并没有回答问题——它没有告诉他为什么字典中不存在那个键。 - agf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接