Python argparse 默认值无法生效

11

我正在尝试使用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

我哪里出错了?


1
您正在使用位置参数而非关键字参数,而未指定适当的 nargs。请阅读 https://docs.python.org/3/library/argparse.html#default。 - jonrsharpe
我可以重现你看到的问题。你可以使用“模式”代替“操作”,但这并不能解决所提出的问题。 - jbcoe
3个回答

6
您缺少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)))

不适用于我。请解释为什么它会起作用。 - Gulzar

5

更改这些行以指示您要使用命名的、可选的命令行参数(因此为"-x"而不是"x"):

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?')

谢谢,它有效!但是有没有办法我可以使用默认值并轻松地使用程序。即键入python cmdline.py应该打印出2.0,键入cmdline.py 3 4应该打印出7。基本上,我想要蛋糕也想吃掉它! - Legion
1
@jbcoe 所以假设你有两个参数,都有不同的默认值,而你只想提供第二个参数。程序如何知道第一个参数获得默认值,而不是第二个参数? - BoarGules
@BoarGules 它不会知道。这是名称参数可以解决的限制。 - jbcoe
太对了!我现在明白了!谢谢伙计! - Legion
@MonkeyBot2020 如果您使用jbcoe的方法,您可以既拥有蛋糕又吃掉它。但前提是默认值必须相同。 - BoarGules

1

@jbcoe - 我认为你的代码中有几个错别字,但是谢谢你,它起作用了!这是解决方案,已经进行了清理:

'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument. It uses the argparse module.'''

import argparse

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=2.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)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接