cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
1429
Views
5
Helpful
3
Replies

Inserting variable in xpath using python maapi

nso20
Level 1
Level 1

Hello,

I was able to insert variable in xpath using python maapi but not for all parameters as below:

myname = 'cisco'

myinterface = 'GigabitEthernet'

mynumber = '1'

with ncs.maapi.Maapi() as m:
    with ncs.maapi.Session(m, 'admin', 'python'):
        with m.start_read_trans() as t:
            root = ncs.maagic.get_root(t)

            mydevice = root.devices.device[myname]  -- ok

            interface = devs.config.ios__interface.GigabitEthernet[mynumber]  -- ok

            interface = devs.config.ios__interface.myinterface[mynumber]  -- NOT ok, tried myinterface with square/curly brackets but no luck.

Can you assist ?

2 Accepted Solutions

Accepted Solutions

vleijon
Cisco Employee
Cisco Employee

The basic problem is: How would Python know that GigabitEthernet is a reference to a field, but myinterface is a reference to a variable that should be resolved? Python solves this by always assuming it is a field reference. You do, however, have a function getattr that you can use.

 

Something like this works:

def ifindepend(device, iftype, ifnum):
    with maapi.single_read_trans('ifindepend', 'system') as t:
       root = ncs.maagic.get_root(t)
       device = root.devices.device[device]
       interfaces = device.config.interface
       interfacetype = getattr(interfaces, iftype)
       interface = interfacetype[ifnum]
       print("IF: {} {}".format(interface, interface._path))

View solution in original post

vleijon
Cisco Employee
Cisco Employee

Yes, that is expected, since that is the name of the list we are in. You can use that _path to get the full path, or just keep grabbing elements under it as normal.

View solution in original post

3 Replies 3

vleijon
Cisco Employee
Cisco Employee

The basic problem is: How would Python know that GigabitEthernet is a reference to a field, but myinterface is a reference to a variable that should be resolved? Python solves this by always assuming it is a field reference. You do, however, have a function getattr that you can use.

 

Something like this works:

def ifindepend(device, iftype, ifnum):
    with maapi.single_read_trans('ifindepend', 'system') as t:
       root = ncs.maagic.get_root(t)
       device = root.devices.device[device]
       interfaces = device.config.interface
       interfacetype = getattr(interfaces, iftype)
       interface = interfacetype[ifnum]
       print("IF: {} {}".format(interface, interface._path))

But print(interface) displays GigabitEthernet only, not GigabitEthernet5 ?

vleijon
Cisco Employee
Cisco Employee

Yes, that is expected, since that is the name of the list we are in. You can use that _path to get the full path, or just keep grabbing elements under it as normal.