如何解决这类KeyError?

时间:2019-06-25 00:26:07

标签: python argparse

我正在尝试编写一个程序来刮取图像以创建用于神经网络的数据集,但是我遇到了一些问题

代码如下:

from imutils import paths
import argparse
import requests
import cv2
import os

ap = argparse.ArgumentParser()
ap.add_argument("-u", "--C:/Users/artus/datasets/urls.txt", 
                required=False, help="path containing URLs")
ap.add_argument("-o", "--C:/Users/artus/datasets/ShoesImage", 
                required=False, help="folder for downloaded images")
args = vars(ap.parse_args())

# grab the list of URLs from the input file, then initialize the
# total number of images downloaded thus far
rows = open(args["urls"]).read().strip().split("\n")
total = 0

执行时,它应该从urls.txt文件中指定的url下载所有图像,但是我遇到此错误:

Traceback (most recent call last):
   File "C:/Users/artus/untitled5/imagescraping.py", line 16, in <module>
    rows = open(args["urls"]).read().strip().split("\n")
KeyError: 'urls'

2 个答案:

答案 0 :(得分:1)

add_argument的第二个参数是参数的“长名称”。对于第一个参数,您将传递--urls,然后argparse将使用户传递的值为args["urls"]

# ...
ap.add_argument("-u", "--urls", type=str,
                required=False, help="path containing URLs")

然后在命令行中传递参数:

python imagescraping.py --urls C:/Users/artus/datasets/urls.txt

此外,我认为您无需将其包装在vars中。

答案 1 :(得分:0)

当我将您的argparse代码复制-n-粘贴到脚本中时:

import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-u", "--C:/Users/artus/datasets/urls.txt", 
                required=False, help="path containing URLs")
ap.add_argument("-o", "--C:/Users/artus/datasets/ShoesImage", 
                required=False, help="folder for downloaded images")
args = ap.parse_args()
print(args)

并在不带参数的情况下调用它:

0923:~/mypy$ python3 stack56745387.py 
Namespace(**{'C:/Users/artus/datasets/ShoesImage': None, 'C:/Users/artus/datasets/urls.txt': None})

并寻求帮助:

1743:~/mypy$ python3 stack56745387.py -h
usage: stack56745387.py [-h] [-u C:/USERS/ARTUS/DATASETS/URLS.TXT]
                        [-o C:/USERS/ARTUS/DATASETS/SHOESIMAGE]

optional arguments:
  -h, --help            show this help message and exit
  -u C:/USERS/ARTUS/DATASETS/URLS.TXT, --C:/Users/artus/datasets/urls.txt C:/USERS/ARTUS/DATASETS/URLS.TXT
                        path containing URLs
  -o C:/USERS/ARTUS/DATASETS/SHOESIMAGE, --C:/Users/artus/datasets/ShoesImage C:/USERS/ARTUS/DATASETS/SHOESIMAGE
                        folder for downloaded images

您可能希望将“ --C:/Users/artus/datasets/urls.txt”设置为默认值,但是您将其定义为long标志,并将其定义为参数dest。 (您的设置中没有将urls指定为所需的dest或键。)

您必须将其用作:

1750:~/mypy$ python3 stack56745387.py --C:/Users/artus/datasets/urls.txt foobar
Namespace(**{'C:/Users/artus/datasets/ShoesImage': None, 'C:/Users/artus/datasets/urls.txt': 'foobar'})

将代码更改为:

import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-u", "--urls", default="C:/Users/artus/datasets/urls.txt", 
                required=False, help="path containing URLs (default: %(default)s)")
ap.add_argument("-o", "--images",default="C:/Users/artus/datasets/ShoesImage", 
                required=False, help="folder for downloaded images (default: %(default)s)")
args = ap.parse_args()
print(args)

1802:~/mypy$ python3 stack56745387.py -h
usage: stack56745387.py [-h] [-u URLS] [-o IMAGES]

optional arguments:
  -h, --help            show this help message and exit
  -u URLS, --urls URLS  path containing URLs (default:
                        C:/Users/artus/datasets/urls.txt)
  -o IMAGES, --images IMAGES
                        folder for downloaded images (default:
                        C:/Users/artus/datasets/ShoesImage)
1803:~/mypy$ python3 stack56745387.py --urls foobar
Namespace(images='C:/Users/artus/datasets/ShoesImage', urls='foobar')

现在您可以使用args.urlsvars(args)['urls']