在 Python 中解析命令行参数:获取 KeyError [英] Parsing command line arguments in Python: getting a KeyError

查看:34
本文介绍了在 Python 中解析命令行参数:获取 KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

python series.py 超自然 4 6

<前>超自然:电视剧名称4 : 季号6:集数

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

导入tvrage.api导入系统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打印(名称.标题)

但我收到此错误:

文件series.py",第 19 行,在  中:名称 = super.season(b).episode(c)文件C:\Python26\Lib\site-packages\tvrage\api.py",第212行,季节返回 self.episodes[n] KeyError: '4'

我使用的是 Python 2.6.

解决方案

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

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

将纠正错误,如果第 4 季第 6 集存在.

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

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.

解决方案

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.

这篇关于在 Python 中解析命令行参数:获取 KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆