Argparse预期一个论点 [英] Argparse expected one argument

查看:35
本文介绍了Argparse预期一个论点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容

import argparse

parser = argparse.ArgumentParser(prog='macc', usage='macc [options] [address]')
parser.add_argument('-l', '--list', help='Lists MAC Addresses')
args = parser.parse_args()
print(args)

def list_macs():
  print("Found the following MAC Addresses")

使用 python macc.py -l <​​/code>运行时收到错误消息,提示需要参数.即使当我将代码更改为 parser.add_argument('-l','--list',help ='列出MAC地址的default = 1')时,我仍然遇到相同的错误.

I get an error when running with python macc.py -l it says that an argument was expected. Even when I change my code to parser.add_argument('-l', '--list', help='Lists MAC Addresses' default=1) I get the same error.

推荐答案

参数的默认操作是 store ,它在 parser返回的名称空间中设置属性的值.使用下一个命令行参数parse_args .

The default action for an argument is store, which sets the value of the attribute in the namespace returned by parser.parse_args using the next command line argument.

您不想存储任何任何特定值;您只想确认使用了 -l <​​/code>.一个快速的技巧是使用 store_true 操作(该操作会将 args.list 设置为 True ).

You don't want to store any particular value; you just want to acknowledge that -l was used. A quick hack would be to use the store_true action (which would set args.list to True).

parser = argparse.ArgumentParser(prog='macc')
parser.add_argument('-l', '--list', action='store_true', help='Lists MAC Addresses')

args = parser.parse_args()

if args.list:
    list_macs()

store_true 操作暗含 type = bool default = False .

但是,一种更简洁的方法是定义一个名为 list 的子命令.使用这种方法,您的调用将是 macc.py list 而不是 macc.py --list .

However, a slightly cleaner approach would be to define a subcommand named list. With this approach, your invocation would be macc.py list rather than macc.py --list.

parser = argparse.ArgumentParser(prog='macc')
subparsers = parser.add_subparsers(dest='cmd_name')
subparsers.add_parser('list')

args = parser.parse_args()

if args.cmd_name == "list":
    list_macs()

这篇关于Argparse预期一个论点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆