【问题标题】:Parsing command line arguments in Python: getting a KeyError在 Python 中解析命令行参数:获取 KeyError
【发布时间】:2011-11-15 18:23:17
【问题描述】:

我正在尝试执行我的 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,但如果你想要错误是`文件“series.py”,第 19 行,在 name = super.season(b).episode( c) 文件“C:\Python26\Lib\site-packages\tvrage\api.py”,第 212 行,in season` return self.episodes[n] KeyError: '4'

标签: python arguments command-line-arguments


【解决方案1】:

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

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

如果存在第 4 季第 6 集,将更正错误。

您应该看看 Python 附带的命令行解析模块。对于 3.2 / 2.7 或更高版本,请使用 argparse。对于旧版本,请使用 optparse。如果你已经知道 C 的getopt,请使用getopt

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • 这是对KeyError 的很好描述,但没有回答问题——它没有告诉他为什么字典中不存在该键。
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2013-02-01
    • 2017-10-29
    • 2020-01-01
    • 1970-01-01
    • 2013-03-21
    相关资源
    最近更新 更多