定义 args 时发生错误
Error occurs upon defining args
这是使用 python2.7
的代码 main.py
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
尽管执行了这些步骤,但我仍然在代码第 4 行出现错误。有什么我做的不对吗?谁能指出我正确的方向?
在交互式 shell 中使用 argparse 效果不佳。 argparse 本质上是从 sys.argv 中提取参数并根据您设置的规则解析它们。正如 raylu 所说,我建议将 python 文件设置为 运行。例如,在名为 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']
然后您可以通过在命令行执行 python test_argparse.py
来测试它。现在可以使用 -1
、--image
、-h
或 --help
标志调用。 -h
和 --help
将为您提供用法。
这是使用 python2.7
的代码main.py
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
尽管执行了这些步骤,但我仍然在代码第 4 行出现错误。有什么我做的不对吗?谁能指出我正确的方向?
在交互式 shell 中使用 argparse 效果不佳。 argparse 本质上是从 sys.argv 中提取参数并根据您设置的规则解析它们。正如 raylu 所说,我建议将 python 文件设置为 运行。例如,在名为 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']
然后您可以通过在命令行执行 python test_argparse.py
来测试它。现在可以使用 -1
、--image
、-h
或 --help
标志调用。 -h
和 --help
将为您提供用法。