我无法传递参数错误:无法识别的参数: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
疯狂物理学家

正如@Dawit的答案正确指出的那样,问题出在action="store_true"内置操作 'store_true'的自动默认False值为,并将命名空间中参数的值设置True为找到该标志的位置。它不接受该标志的任何参数。

如果要接受该标志的参数,则必须使用类似的操作action="store"

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章