繁体   English   中英

使用 jupyter notebook 运行代码时出现 argparse 错误

[英]Error in argparse when running the code using jupyter notebook

我正在关注数据风格教程,一切都运行良好,除非涉及到这个:

ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help="Image Path")
args = vars(ap.parse_args())
img_path = args['image']

它给了我这个错误,

错误

我尝试在文本文件中编写代码,然后将其另存为 .py 文件,但它给出了相同的错误。

代码没问题,但你运行不正确。

您应该使用-i--image以及image's filename/full/path/to/image运行它

!python example.py -i lenna.png

!python example.py --image lenna.png

!python example.py -i /home/furas/images/lenna.png

!python example.py --image /home/furas/images/lenna.png

并且help=" "仅在您运行时显示信息

!python example.py --help

或更短

!python example.py -h

结果:

usage: example.py [-h] -i INPUT

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT, --input INPUT
                        Image Path

在第二列中,它显示了help="Image Path" Image Path的图像路径。

您可以将其更改为更易读的内容,例如help="put path to image" ,然后您会得到

usage: example.py [-h] -i INPUT

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT, --input INPUT
                        put path to image

[-h]中的括号[]表示-h是可选的。

-i INPUT表示它是必需的,并且它需要一些值来代替INPUT

它还表明您可以使用:

  • --help而不是-h
  • --image代替-i

顺便提一句:

而不是两行

args = vars(ap.parse_args())
img_path = args['image']

你可以直接运行

img_path = ap.image

暂无
暂无

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

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