简体   繁体   English

为什么即使我写正确,argparse也不起作用并发送无效的选项错误消息?

[英]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). 当我正确使用argparse时,选项字符串错误无效(来自python教育网站的示例文件)。

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. 我更改了参数--input和--output->输入和输出文件的路径。

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. arg_parse.addargument()的第二个位置参数是您要用来引用变量的名称的长版本,因此-i将是--input ,如果需要,则需要使用default=...参数希望它具有默认值。 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: 或者,如果您想要-i-o的默认值,则可以使用argparser的默认参数:

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

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

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