Python 2.7 Argparse 是否输入 Yes 或 No

3

我正在尝试使用argparse创建一个实例,在该实例中,我可以在Unix控制台中输入:

python getFood.py --food <(echo Bread) --calories yes

我已经实现了食品选项,并希望使用argparse添加一个卡路里“是”或“否”的选项(二进制输入),以确定是否从我导入的类中调用calories方法。
我的当前主要代码如下:
parser = argparse.ArgumentParser(description='Get food details.')
parser.add_argument('--food', help='name of food to lookup', required=True, type=file)
args = parser.parse_args()

这成功地允许我使用上面显示的第一个食品选项,返回食品详细信息。

基本上,我想添加第二个二进制选项,如果用户指示为true,则调用另一种方法。有没有帮助我如何编辑我的主要例程argparse参数?我对argparse仍然非常陌生。


什么?我理解所有的单词,但我不明白你想做什么。 - Joran Beasley
type=file 可以工作,但可能不会达到您的预期。在 Python2 中,file 与打开文件的函数 open 相同。因此,是的,您可以执行 args.food.read()type=argparse.FileType('r') 可以更好地控制文件的打开方式。在 Python3 中,file 未定义。 - hpaulj
1个回答

14

您可以简单地添加一个参数action='store_true',如果未包括--calories,则默认将args.calories设置为False。进一步澄清,如果用户添加了--caloriesargs.calories将被设置为True

parser = argparse.ArgumentParser(description='Get food details.')
# adding the `--food` argument

parser.add_argument('--food', help='name of food to lookup', required=True, type=file)
# adding the `--calories` argument
parser.add_argument('--calories', action='store_true', dest='calories', help='...')
# note: `dest` is where the result of the argument will go.
# as in, if `dest=foo`, then `--calories` would set `args.foo = True`.
# in this case, it's redundant, but it's worth mentioning.

args = parser.parse_args()

if args.calories:
    # if the user specified `--calories`, 
    # call the `calories()` method
    calories()
else:
    do_whatever()

如果您想具体检查是否为yesno,则更改中的store_true

parser.add_argument('--calories', action='store_true', dest='calories', help='...')

使用 store,如下所示

parser.add_argument('--calories', action='store', dest='calories', type='str', help='...')

这样做将使您稍后能够进行检查。

if args.calories == 'yes':
    calories()
else:
    do_whatever()

需要注意的是,在这个例子中,我添加了type=str,它将参数解析为字符串。由于您指定的选项要么是yes,要么是noargparse实际上允许我们使用choices进一步指定可能输入的域:

parser.add_argument('--calories', action='store', dest='calories', type='str', 
                    choices=['yes', 'no'], help='...')

现在,如果用户输入的不是['yes', 'no']中的任何一个,它将会引发一个错误。

最后一种可能性是添加一个 default,这样用户就不必每次都指定某些标志:

parser.add_argument('--calories', action='store', dest='calories', type='str', 
                    choices=['yes', 'no'], default='no', help='...')

编辑:正如@ShadowRanger在评论中指出的,本例中dest='calories'action='store'type='str'是默认值,因此您可以省略它们:

parser.add_argument('--calories', choices=['yes', 'no'], default='no', help='...')

我认为这是正确的答案......但从原始问题中无法确定......解析得很好,加1(我认为您不需要dest参数) - Joran Beasley
3
注意:action =“store”dest ='calories'已经是默认设置。对于action =“store”type ='str'也是默认设置。因此,您可以省略所有这些,并只执行以下操作:parser.add_argument('--calories',choices =('yes','no'),default ='no',help ='...') - ShadowRanger
1
是的,@ShadowRanger说得很好。我添加了额外的参数来说明add_argument中的其他可能性,但我会重申你上面的观点。 - Michael Recachinas

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