在Python中解析命令行参数:出现KeyError

3 投票
2 回答
3047 浏览
提问于 2025-04-17 02:09

我正在尝试这样运行我的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版本。

2 个回答

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 上关于 KeyError 的介绍

3

Python TVRage API 这个工具需要你传入整数,而不是字符串(你从 argv 得到的就是字符串)。

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

如果第四季第六集存在,这样做就能修正错误。

你应该看看 Python 自带的命令行解析模块。对于 3.2 / 2.7 或更新的版本,可以使用 argparse。如果你用的是旧版本,可以使用 optparse。如果你已经了解 C 语言的 getopt,那么可以使用 getopt

撰写回答