简体   繁体   中英

Error in argparse when running the code using jupyter notebook

I'm following a data-flair tutorial and everything is working well except when it comes to this:

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

it gives me this error,

错误

I tried writing the code in text file then save it as.py file but it gives the same error.

Code is OK but you run it incorrectly.

You should run it with -i or --image and with image's filename or with /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

And help=" " is only to display information when you run it as

!python example.py --help

or shorter

!python example.py -h

Result:

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

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

In second column it shows Image Path which was in help="Image Path" .

You can change it to something more readable like help="put path to image" and you get

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

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

Brackets [] in [-h] means that -h is optional.

-i INPUT means that it is required and it needs some value in place of INPUT .

It also shows that you can use:

  • --help instead of -h
  • --image instead of -i

BTW:

Instead of two lines

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

you can run directly

img_path = ap.image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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