Sea*_*ean 2 python unix python-2.7 argparse
我正在尝试使用argparse来创建一个我在Unix控制台中键入的实例:
python getFood.py --food <(echo Bread) --calories yes
Run Code Online (Sandbox Code Playgroud)
我已经实现了食物选项,并希望使用argparse添加卡路里是或否选项(二进制输入),这将决定是否从我导入的类调用卡路里方法.
我目前的代码主程序是:
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()
Run Code Online (Sandbox Code Playgroud)
这成功地允许我使用上面显示的第一个食物选项返回食物细节.
基本上我想添加第二个二进制选项,如果用户指示为true,将调用另一个方法.有关如何编辑我的主例程argparse参数的任何帮助?我对argparse还很新.
Mic*_*nas 11
您可以简单地添加一个参数action='store_true',args.calories如果--calories未包含参数,则默认为False .为了进一步说明,如果用户添加--calories,args.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()
Run Code Online (Sandbox Code Playgroud)
但是,如果您想要专门检查yes或no,则替换store_truein
parser.add_argument('--calories', action='store_true', dest='calories', help='...')
Run Code Online (Sandbox Code Playgroud)
用store,如下图所示
parser.add_argument('--calories', action='store', dest='calories', type='str', help='...')
Run Code Online (Sandbox Code Playgroud)
这将允许您稍后检查
if args.calories == 'yes':
calories()
else:
do_whatever()
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下我添加了type=str,它将参数解析为字符串.由于您指定选项是yes或者no,argparse实际上允许我们使用以下内容进一步指定可能输入的域choices:
parser.add_argument('--calories', action='store', dest='calories', type='str',
choices=['yes', 'no'], help='...')
Run Code Online (Sandbox Code Playgroud)
现在,如果用户输入任何不在的内容['yes', 'no'],则会引发错误.
最后一种可能性是添加a default,这样用户不必一直指定某些标志:
parser.add_argument('--calories', action='store', dest='calories', type='str',
choices=['yes', 'no'], default='no', help='...')
Run Code Online (Sandbox Code Playgroud)
编辑:@ShadowRanger在评论中指出,在这种情况下,dest='calories',action='store',和type='str'是默认值,所以你可以忽略它们:
parser.add_argument('--calories', choices=['yes', 'no'], default='no', help='...')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2001 次 |
| 最近记录: |