Parsing command line arguments in Python: getting a KeyError

筅森魡賤 提交于 2021-01-27 11:43:00

问题


I am trying execute my Python script as:

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.


回答1:


The Python TVRage API is expecting integers, not strings (which is what you get from argv):

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

will correct the error, if season 4 episode 6 exists.

You should take a look at the command line parsing modules that come with Python. For 3.2 / 2.7 or newer, use argparse. For older versions, use optparse. If you already know C's getopt, use getopt.




回答2:


A KeyError means you're trying to access an item in a dictionary that doesn't exist. This code will generate the error, because there's no 'three' key in the dictionary:

>>> 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.



来源:https://stackoverflow.com/questions/7395488/parsing-command-line-arguments-in-python-getting-a-keyerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!