gpt4 book ai didi

python - 属性错误 : 'Namespace' object has no attribute 'check'

转载 作者:太空狗 更新时间:2023-10-29 22:02:12 25 4
gpt4 key购买 nike

我正在尝试在命令行上使用不同的参数运行 python 脚本。有一个位置参数( num ),其他是可选参数。我尝试运行 [ python newping.py 10 -c ] 但出现以下错误。有什么我无法弄清楚的错误吗?

import argparse

def fibo(num):
a,b = 0,1
for i in range(num):
a,b=b,a+b;
return a;

def Main():
parser = argparse.ArgumentParser(description="To the find the fibonacci number of the give number")
arg1 = parser.add_argument("num",help="The fibnocacci number to calculate:", type=int)
arg2 = parser.add_argument("-p", "--password", dest="password",action="store_true", help="current appliance password. Between 8 and 15 characters, lower case, upper case and numbers")
arg3 = parser.add_argument("-i", "--ignore",help="ignore the args",action="store_true", dest="ignore")
arg4 = parser.add_argument("-c", "--check", help="performance metrics",action="store_true", dest="performance")
arg5 = parser.add_argument("-m", "--node/model",dest="Node_Model",help="Type of the Model",action="store_true")
parser.add_argument("-pf", "--permfile", help="increase output verbosity",action="store_true")
args = parser.parse_args()

result = fibo(args.num)
print("The "+str(args.num)+"th fibonacci number is "+str(result))

if args.permfile:

for x in range(1,len(vars(args))):
value = locals()["arg"+str(x)]
print(value.dest+ " "+ value.help)

if args.password:
print("I am asking for the password")

if args.ignore:
print("This is to ignore the command")

if args.check:
print("Check the performance of the server")


if __name__ == '__main__':
Main()


Output :
The 10th fibonacci number is 55
Traceback (most recent call last):
File "newping.py", line 41, in <module>
Main()
File "newping.py", line 36, in Main
if args.check:
AttributeError: 'Namespace' object has no attribute 'check'

最佳答案

当你创建参数时

arg4 = parser.add_argument("-c", "--check", help="performance metrics",
action="store_true", dest="performance")

dest 参数告诉 argparse 使用名为 performance 的变量,而不是 check。将您的代码更改为:

if args.performance:
print("Check the performance of the server")

或删除 dest 参数。

Python 风格指南建议您将行限制为 80 个字符,这在发布到 SO 时很有帮助,这样我们就不必滚动查看代码。

关于python - 属性错误 : 'Namespace' object has no attribute 'check' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126551/

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