Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error occurs upon defining args

Here's the code main.py using python2.7

import argparse
import cv2

ap = argparse.ArgumentParser()

ap.add_argument("-1","--image", required = True, help = "Path to the image")
Out[4]: _StoreAction(option_strings=['-1', '--image'], dest='image', 
nargs=None, const=None, default=None, type=None, choices=None, help='Path to 
the image', metavar=None)

args = vars(ap.parse_args())

usage: main.py [-h] -1 IMAGE main.py: error: argument -1/--image is required To exit: use 'exit', 'quit', or Ctrl-D. An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

I keep getting error on code line 4 despite following the steps. Is there something I'm not doing right? Can anyone point me in the right direction?

like image 809
patrick.c Avatar asked Aug 12 '26 13:08

patrick.c


1 Answers

Using argparse from within the interactive shell will not work well. What argparse essentially does it extract arguments from sys.argv and parse them according to the rules that you set up. As raylu said, I would suggest setting up a python file to run. For example, in a file called test_argparse.py:

import argparse
import cv2

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-1","--image", required = True, help = "Path to the image")
    args = vars(ap.parse_args())
    print args['image']

You can then test this by executing python test_argparse.py at the commandline. This can now be called with the -1, --image, -h, or --help flags. -h and --help will provide you usage.

like image 110
Vorticity Avatar answered Aug 14 '26 11:08

Vorticity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!