解析Python中的命令行参数:获取KeyE

2024-03-28 12:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Python脚本执行为:

python series.py supernatural 4 6
^{pr2}$

现在在我的脚本中,我使用上述三个参数来获取该集的标题:

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'

我使用的是python2.6。在


Tags: nameinpyimport脚本apisysline
2条回答

Python TVRage API需要的是整数,而不是字符串(这是从argv得到的):

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

如果第四季第六集存在的话,将会更正错误。在

您应该看看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'

the Python Wiki entry on KeyErrors。在

相关问题 更多 >