python - Python argparse默认值不起作用
问题描述
我正在尝试使用 argparse,程序可以工作,但默认值不起作用。这是我的代码:
'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.'''
import argparse
import sys
def calc(args):
#Enable variables within the function to take on values from 'args' object.
operation = args.operation
x = args.x
y = args.y
if (operation == "add"):
return x + y
elif (operation == "sub"):
return x - y
parser = argparse.ArgumentParser(description="This is a summing program") #parser is an object of the class Argument Parser.
parser.add_argument("x", type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("y", type=float, default=1.0, help='What is the second number?')
parser.add_argument("operation", type=str, default="add", help='What operation? Can choose add, sub, mul, or div')
args = parser.parse_args()
print(str(calc(args)))
这个简单的程序工作,但是尝试在没有值的情况下调用它会返回以下错误:
usage: cmdline.py [-h] x y operation
cmdline.py: error: the following arguments are required: x, y, operation
我哪里错了?
解决方案
你失踪了nargs='?'
。以下作品:
import argparse
import sys
def calc(args):
#Enable variables within the function to take on values from 'args' object.
operation = args.operation
x = args.x
y = args.y
if (operation == "add"):
return x + y
elif (operation == "sub"):
return x - y
parser = argparse.ArgumentParser(description="This is a summing program") #parser is an object of the class Argument Parser.
parser.add_argument("x", nargs='?', type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("y", nargs='?', type=float, default=1.0, help='What is the second number?')
parser.add_argument("operation", nargs='?', type=str, default="add", help='What operation? Can choose add, sub, mul, or div')
args = parser.parse_args()
print(str(calc(args)))
推荐阅读
- java - Java ~ 用户按用户
- game-engine - 如果可以不用编码就可以制作游戏,为什么还要编码呢?
- javascript - 将一组未删节的连续字符串值解析为可用的可索引键值对
- php - 在自定义路由中使用 register_rest_field
- kubernetes - 在 Kubernetes 集群中捕获来自 Pod 的传出请求并重定向到不同的目标
- javascript - Laravel 与 ajax vanila javascript
- java - 如何检索表示结果集中总和的“总”变量
- python - 如何在情节中显示漏斗图中的所有数字?
- sql - ORDER BY date 但保留 GROUP BY 分组
- javascript - 合并 2 个变化中的数组