gpt4 book ai didi

python - 我无法传递参数错误 : unrecognized arguments: Argparse Python3

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:32 24 4
gpt4 key购买 nike

我正在使用 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's answer正确指出,问题出在 action="store_true" 上。内置 action 'store_true' 的自动默认值为 False,如果找到标志,则将命名空间中的参数值设置为 True。它不接受标志的任何参数。

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

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

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

关于python - 我无法传递参数错误 : unrecognized arguments: Argparse Python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com