Argparse 错误 python 3.6

Error in Argparse python 3.6

这是我使用的代码;我 运行 在 Anaconda 中使用 Python 3.6:

from imutils.perspective import four_point_transform
from imutils import contours

import numpy as np
import argparse
import imutils
import cv2

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

我得到一个错误:

runfile('/Users/suryavamsi/untitled5.py', wdir='/Users/suryavamsi')
usage: untitled5.py [-h] -1 IMAGE
untitled5.py: error: the following arguments are required: -1/--image
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

/Users/suryavamsi/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2870: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

您是 运行 命令行脚本 在您的 IDE 中,使用 runfile() 命令且没有命令行参数。

argparse 工作正常。缺少必需的参数(因为在使用 runfile() 时未设置 sys.argv),因此使用正确的错误代码引发 SystemExit exception 以退出命令行脚本。

您似乎在使用 Spyder,在这种情况下,您必须使用 Run > Configuration per file 选项设置命令行选项,并将命令行选项添加到 Command line options 框中。参见 Not sure how to use argv with Spyder