I can´t pass the arguments error: unrecognized arguments: Argparse Python3

I can´t pass the arguments error: unrecognized arguments: Argparse Python3

我正在使用 python 3.6,我正在尝试编写一个需要参数的程序,但我无法使用它,因为我无法传递参数。还有一个问题:dest这个参数看不懂;是用那个名字创建一个变量吗?

#!/usr/bin/env python3
import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mac',
                    help='Introduce your new MAC' +
                    'use random as value if you want to have a random mac',
                    action="store_true", required=True)
parser.add_argument('-i', '--interface',
                    help='The interface that the MAC will be changed',
                    action="store", required=True)
args = parser.parse_args()

print(args.mac + args.interface)

我在尝试使用它时遇到此错误(我使用 hi 和 bye 作为示例)

> python  '.\test.py' -m hi -i bye
usage: test.py [-h] -m -i INTERFACE
test.py: error: unrecognized arguments: hi

这对我有用:

parser.add_argument('-m', '--mac',
                help='Introduce your new MAC' +
                'use random as value if you want to have a random mac',
                action="store", required=True

store_true 更改为 store

因为 correctly points out, the issue is with action="store_true". The built-in action 'store_true' 具有自动默认值 False,如果找到标志,则将命名空间中的参数值设置为 True。它不接受标志的任何参数。

如果你想接受标志的参数,你必须使用像 action="store".

这样的动作

如果您想当场进行错误检查或转换您的参数,请传递 type to add_argument。您可以转换为 int 之类的类型,或者只检查您的参数。例如,您可以使用一个函数 mac_address 将参数字符串解析为更易于管理的对象,或者在格式不匹配时引发错误。然后你可以做 type=mac_address.

dest 参数仅提供命名空间中要为其分配值的输出属性的名称。这通常取自标志或位置参数的长名称。因此,对于 --mac,输出变量将默认为 mac,对于 --interface,它将默认为 interface。不过,有时您想使用替代输出变量。