gpt4 book ai didi

Python argparse 默认值不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:58 28 4
gpt4 key购买 nike

我正在试验 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)))

关于Python argparse 默认值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410165/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com