我正在使用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"
。
如果要当场进行错误检查或转换参数,请传递type
给add_argument
。您可以将其转换为int
,或者只检查您的参数。例如,您可以使用一个函数mac_address
,将参数字符串解析为一个更易于管理的对象,或者在格式不匹配时引发错误。那你可以做type=mac_address
。
该dest
参数仅提供名称空间中输出属性的名称,以将值分配给该名称。通常这是从标志或位置参数的长名称中获取的。因此,--mac
对于输出变量将默认为mac
,对于--interface
其将默认为interface
。有时,您可能想要使用替代输出变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句