简体   繁体   中英

Why doesn't argparse work and send invalid option error message even if i wrote correctly?

There is invalid option string error when i use argparse correctly (example file from python education website).

I tried changed the path of input and output file and symbols like \\ -> / or \\ in the path

the original code was

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input image")
ap.add_argument("-o", "--output", required=True,
    help="path to output image")
args = vars(ap.parse_args())

and i changed argument --input and --output -> path of input and output files.

ap = argparse.ArgumentParser()
ap.add_argument("-i", "C:\input_01.png", required=True,
    help="path to input image")
ap.add_argument("-o", "C:\output_011.png", required=True,
    help="path to output image")
args = vars(ap.parse_args())

and i got this error message.

Traceback (most recent call last):
  File "C:/Users/command-line-arguments/shape_counter.py", line 13, in 
<module>
    help="path to input image")
  File "C:\Users\huryo\Anaconda3\lib\argparse.py", line 1339, in add_argument
    kwargs = self._get_optional_kwargs(*args, **kwargs)
  File "C:\Users\huryo\Anaconda3\lib\argparse.py", line 1470, in _get_optional_kwargs
    raise ValueError(msg % args)
ValueError: invalid option string 'C:\\input_01.png': must start with a character '-'

The second positional argument for arg_parse.addargument() is the long version of the name you want to use to refer to a variable by, so -i would be --input , you need to use the default=... argument if you want it to have a default value. You should change your code back to:

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input image")
ap.add_argument("-o", "--output", required=True,
    help="path to output image")
args = vars(ap.parse_args())

or, if you want a default for the -i and -o you can use the argparser's default argument:

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", default="C:\input_01.png",
    help="path to input image")
ap.add_argument("-o", "--output", default="C:\output_011.png",
    help="path to output image")
args = vars(ap.parse_args())

and then call it from the command line with the command line arguments:

python shape_counter.py -i C:\\input_01.png -o C:\\output_011.png

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