标题几乎概括了我希望发生的事情。
我想执行一个 python 脚本来处理 IP 地址和社区字符串。
我使用以下命令进行解析:
import argparse
def get_args():
'''This function parses and return arguments passed in'''
# Assign description to the help doc
parser = argparse.ArgumentParser(
description='')
# Add arguments
parser.add_argument(
'-i', '--ip-adress', type=str, help='ip address of the host', required=True)
parser.add_argument(
'-c', '--community', type=str, help='community string', required=True)
# Array for all arguments passed to script
args = parser.parse_args()
# Assign args to variables
IP = args.ip-adress
COMMUNITY = args.community
# Return all variable values
return IP ,COMMUNITY
# Run get_args()
# get_args()
# Match return values from get_arguments()
# and assign to their respective variables
IP , COMMUNITY = get_args()
# Print the values
print "\n ip address : [ %s ]\n" % IP
print "\ncommunity: [ %s ]\n" % COMMUNITY
但是,无论我如何处理该参数,我都无法弄清楚为什么会出现此错误。
python arg.py -i 10.0.1.2 -c xxbsd
Traceback (most recent call last):
File "arg.py", line 30, in <module>
IP , COMMUNITY = get_args()
File "arg.py", line 20, in get_args
IP = args.ip-adress
AttributeError: 'Namespace' object has no attribute 'ip'
有人能帮忙吗?
请您参考如下方法:
您应该使用 args.ip_adress 而不是 args.ip-adress。
已编辑:
- 符号是减法,不能用在变量名中。 argparse 会将其转换为变量 args.ip_address,因此使用它,您将获得金币
