Argparse 需要一个参数 [英] Argparse expected one argument
问题描述
我有以下内容
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
运行时遇到错误,它说需要一个参数.即使我将代码更改为 parser.add_argument('-l', '--list', help='Lists MAC Addresses' 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
.一个快速的技巧是使用 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
.
The store_true
action implies type=bool
and default=False
as well.
然而,一个稍微简洁的方法是定义一个名为 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屋!