简体   繁体   English

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

[英]Parsing command line arguments in Python: getting a KeyError

I am trying execute my Python script as: 我正在尝试执行我的Python脚本:

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

Now in my script I am using the above three arguments to fetch the title of the episode: 现在在我的脚本中我使用上面的三个参数来获取剧集的标题:

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)

But I am getting this error: 但是我收到了这个错误:

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'

I am using Python 2.6. 我使用的是Python 2.6。

The Python TVRage API is expecting integers, not strings (which is what you get from argv ): Python TVRage API期望整数,而不是字符串(这是你从argv得到的):

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

will correct the error, if season 4 episode 6 exists. 如果第4季第6集存在,将纠正错误。

You should take a look at the command line parsing modules that come with Python. 您应该看一下Python附带的命令行解析模块。 For 3.2 / 2.7 or newer, use argparse . 对于3.2 / 2.7或更高版本,请使用argparse For older versions, use optparse . 对于旧版本,请使用optparse If you already know C's getopt , use getopt . 如果您已经知道C的getopt ,请使用getopt

A KeyError means you're trying to access an item in a dictionary that doesn't exist. KeyError意味着您正在尝试访问不存在的字典中的项目。 This code will generate the error, because there's no 'three' key in the dictionary: 此代码将生成错误,因为字典中没有'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'

See the Python Wiki entry on KeyErrors . 请参阅KeyErrors上的Python Wiki条目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM