Spyder(python 3.6) 运行含argparse模块的程序
1 2 3 4 5 6 7 8 9 10 11 12 | # max sum.py import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers)) |
出现如下错误:
usage: max sum.py [-h] [–sum] N [N …]
max sum.py: error: the following arguments are required: N
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
E:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2971: UserWarning: To exit: use ‘exit’, ‘quit’, or Ctrl-D.
warn(“To exit: use ‘exit’, ‘quit’, or Ctrl-D.”, stacklevel=1)

错误原因:
没有输入参数
解决办法:
打开Anaconda Prompt 或 cmd.exe,用 命令 python xx.py 参数 执行。


参考:https://docs.python.org/zh-cn/3.6/library/argparse.html#argumentparser-objects
another example:
1 2 3 4 5 6 7 8 9 10 11 | # temp.py import argparse parser = argparse.ArgumentParser() # 声明一个parser parser.add_argument("parg") # 位置参数,第一个出现的参数赋值给parg parser.add_argument("--digit",type=int,help="输入数字") # 通过 --echo xxx声明的参数,为int类型 parser.add_argument("--name",help="名字",default="default") # 同上,default 表示默认值 args = parser.parse_args()# 读取命令行参数 # 调用这些参数 print(args.parg) print("echo ={0}".format(args.digit)) print("name = {}".format(args.name)) |
