How to use argparse IP address and community string?

Viewed 4758

The title pretty much summarizes what I'd like to have happen.

I want to execute a python script that does something with IP address and community string.

I use the following command for parsing:

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

However, no matter how I played with the argument I cannot figure out why I get this error.

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'

Could anyone help?

3 Answers

Instead of args.ip-adress you should use args.ip_adress.

EDITED:

the - symbol is subtraction and may not be used in variable names. argparse will translate it to the variable args.ip_address, so use that and you'll be golden

I think you can't use the dash in the variable name, because Python will interpret it as args.ip minus adress.

You can change the variable name to args.ipaddress and it should work.

To have complete control on the variable names you can specify your own name

parser.add_argument(... dest=my_var ...)
Related