Need help my python script showing index error - python

From below configuration, i need to pull hostname and Group-name neighbor x.x.x.x information,
#
-set system host-name devicename_ABC
-set protocols bgp group Group-name type internal
-set protocols bgp group Group-name neighbor x.x.x.x
-set protocols bgp group Group-name neighbor z.z.z.z
#
I wrote below python script but it showing index error. please help me to solve this problem.
Python script :
reDeviceName = re.compile(r'#\s*\n\s*host (\S*)\s*',re.DOTALL)
deviceName = reDeviceName.findall(allText)
regBbpGroup = re.compile(r'\s*bgp group (\S*)\s*',re.DOTALL)
bpGroupList = regBbpGroup.findall(allText)
numBbpGroup = len(bpGroupList)
i = 0
def temp(x):
return x
while i < numBbpGroup:
requiredInfo = list(map(temp,bpGroupList[i]))
requiredInfo.insert(0,deviceName[0]) (index error showing for this line)
bpGroupList = str(requiredInfo[2])
i = i + 1

numBbpGroup = len(bpGroupList) - 1
Use this and it will work fine for you. Length function in python starts counting from 1 and array indexing starts at 0

Edit: This is not the cause of your current IndexError, however if you only fix your device name string regex expression, you will get another IndexError when you try to access bpGroupList[i] when i = len(bpGroupList).
Change your while loop into for loop. Another answer suggested subtracting 1 from your numBbpGroup variable, but then the name of the variable would be misleading. The range function is designed to operate in this minus 1 fashion. So instead of saying
while i < numBbpGroup:
...
i = i + 1
you can say
for i in range(numBbpGroup):
...
and it will work fine. i will go from 1 up to numBbpGroup - 1 that you don't need to increment i in the for-loop version.
Edit: I have a feeling your device name variable is an empty string, which is what's causing the index error you see.

Can you try this positive look-behind regular expression instead? I'm assuming you want the test after the string host-name.
reDeviceName = re.compile(r'(?<=host-name).*')

Related

printing the values of an Array prevents a null pointer error

I'm trying to search a parameter space for a good model. In my code I'm doing something like the following:
configurations = [None] * 9
index = 0
for param1 in range(3):
for param2 in range (3):
#call constructor
configurations[index] = Configuration(param1, param2)
index = index + 1
return configurations
then I use this array elsewhere to build the models.
However, for some reason it doesn't fill the array. I get an error when accessing index 3 or higher. Inspection shows that the array at these indices are still 'None'. while debugging this, I added a print statement to the code:
configurations = [None] * 9
index = 0
for param1 in range(3):
for param2 in range (3):
#call constructor
configurations[index] = Configuration(param1, param2)
index = index + 1
for x in configurations:
print(x.param1)
return configurations
to my surprise, my code now ran smoothly. The array is completely filled. If I comment out those 2 lines: error. uncomment the lines: it works again.
what is going on here? Why is the print statement altering the behavior of my program? is this an overactive GC that's staved off by printing the values?
I found the issue. the return statement was indented with a Tab, but I use 4 spaces everywhere else in my code. This was causing it to skip the most outer for loop. the print statement somehow prevented this. changing the tab to spaces removed the need for the print statement.

My python programm keep printing the same id event if i want it to print the others too

I'm new in your community but i have a problem on one of my code.I am developping a program which is use to summerize the shell command 'show vlan' and 'show mac address-table' to a table with only the informations we want it to print. Those informations are the vlan Ids of the switch we are using, the number of vlan per mac adresses and the number of mac adresses which are dynamic. Unfortunately, it keep on printing only one vlan id and not the others of the switch, and it's always the same one.i'd like to resolve the problem. I'm a junior on python and i'm pretty sure my code is wrong somewhere but i don't know where.
i used this example of the devnet website to find a way to code what i was asked to code:
an example of the command 'show interface brief' in a code from devnet website
This is my code:
import json
import cisco
from cli import *
shVlan = json.loads(clid('show vlan'))
shMacAdr = json.loads(clid('show mac address-table'))
mac_counter = 0
print(' | VlanId | #Mac/vlan')
print('--|--------|-----------')
for i in range (0, len(shVlan['TABLE_vlanbrief']['ROW_vlanbrief'])):
vlan = shVlan['TABLE_vlanbrief']['ROW_vlanbrief'][i]
vlanId = int(vlan['vlanshowbr-vlanid'])
for j in range (0, len(shMacAdr['TABLE_mac_address'] ['ROW_mac_address'])):
mac_adr = shMacAdr['TABLE_mac_address']['ROW_mac_address'][j]
if mac_adr['disp_vlan'] == vlan['vlanshowbr-vlanid']:
mac_counter = mac_counter + 1
total_mac_dyn = 0
for k in range (0, len (shMacAdr['TABLE_mac_address']['ROW_mac_address'])):
mac = shMacAdr['TABLE_mac_address']['ROW_mac_address'][k]
if mac['disp_is_static'] == 'disabled':
total_mac_dyn = total_mac_dyn + 1
l = 0
while l < len(shVlan['TABLE_vlanbrief']['ROW_vlanbrief']) and l < len(shMacAdr['TABLE_mac_address']['ROW_mac_address']):
l = l +1
print('%2d| %5d | %5d') % (l, vlanId, mac_counter)
print('--|--------|-----------')
print('Total #Mac dynamiques| %2d') % (total_mac_dyn)
print('---------------------|----')
i used the sandbox of cisco to find the table of my switch:
i asked:
the command show vlan
and i converted it so i can see what's inside the switch, that is what i took for my table shVlan (in my code):
the answer from the cisco sandbox for a show vlan
then i did the same with the 'show mac-address table' command:
show mac address-table ask
and i converted it so i could see what was inside the switch so that i could use it for my table shMacAdr(in my code):
that's the answer of the convertion:
answer of the sandbox for 'show mac address-tabe' command
and that's the out put of my code with the command 'pyhton bootflash:/scripts(because it's in scripts doc)/ mac_vlan.py(because it's the name of my file)':
out put of my code which keep printing only one id
I hope i made it clearer i still don't understand well how to make myself understandable sorry for the screens that's the only thing i found to illustrates how i thoght for creating my code.
There are many things you can learn to improve your code.
1) Looping through array:
When you are looping through an array you can use
for array_element in array:
another_array.append(array_element)
2) When you wanted to loop through 2 or more arrays at the same time, you can use zip
for element1, element2 in zip(array1, array2):
# do something with element1 and element2
using zip you'll achieve the same functionality as you obtain using
while i < len(array1) and i < len(array2):
element1 = array1[i]
element2 = array2[i]
i = i + 1
So replace the for i loop and for j loop and last while loop with the following code
mac_counter = 0
for vlan, mac_addr in zip(shVlan['TABLE_vlanbrief'][['ROW_vlanbrief'], shMacAdr['TABLE_mac_address']['ROW_mac_address']):
vlanId = int(vlan["vlanshowbr-vlanid"])
# same with mac_addr
# test fields of mac_addr and update mac_counter
# print them
My question have been solved thank you all for your help and your kindness towards me!
Have a nice day!
vlanId going to be overwritten at every iteration your loop does.
Therefor you always get only the last Id back that have been found.
you better use a list and append the different Ids

Where do I add in an re.search in this python code?

I have some python code to change the severities of incoming SNMP traps on the NMS I am using.
The incoming SNMP traps contain objects that are ranges of numbers for a given severity level. The below code works if the the incoming object numbers are singular, 1,2,3,4,5 etc. But it doesnt work for the below when trying to match a regex number range.
## This gets the alarmTrapSeverity function and creates a variable called Severity to hold the value
if getattr(evt, 'alarmTrapSeverity', None) is not None:
Severity = getattr(evt, 'alarmTrapSeverity')
## This part runs through the Severity to assign the correct value
if str(Severity) == '0':
evt.severity = 0
elif str(Severity) == '([1-9]|1[0-9])':
evt.severity = 1
Please could you advise the correct way to do this. My regex skills are still developing.
If I am understanding this correctly, in the else-if statement you would like to perform a regular expression search in order to confirm a match. My approach would look like this,
## This gets the alarmTrapSeverity function and creates a variable called
Severity to hold the value
if getattr(evt, 'alarmTrapSeverity', None) is not None:
Severity = getattr(evt, 'alarmTrapSeverity')
regex = re.compile(r'([1-9]|1[0-9])')
## This part runs through the Severity to assign the correct value
if str(Severity) == '0':
evt.severity = 0
elif regex.search(str(Severity)) != None:
evt.severity = 1
This would search the str(Severity) variable for a matching substring, which in this case would be the string containing numbers between 1-19. Then as long as it finds a match, sets evt.severity = 1.
Also, looking back at your question, if you were having issues with finding numbers between 1-19 with that regex, another example which works might be,
"10|1?[1-9]"

Maya Python skinCluster return type not string?

I'm trying to check if an object has a skinCluster on it. My code is pretty basic. Here's an example:
cmds.select(d=True)
joint = cmds.joint()
skinnedSphere = cmds.polySphere(r=2)
notSkinnedSphere = cmds.polySphere(r=2)
skinTestList = [skinnedSphere, notSkinnedSphere]
# Bind the joint chain that contains joint1 to pPlane1
# and assign a dropoff of 4.5 to all the joints
#
cmds.skinCluster( joint, skinnedSphere, dr=4.5)
for obj in skinTestList:
objHist = cmds.listHistory(obj, pdo=True)
skinCluster = cmds.ls(objHist, type="skinCluster")
if skinCluster == "":
print(obj + " has NO skinCluster, skipping.")
else:
print obj, skinCluster
#cmds.select(obj, d=True)
My issue is that even if it can't find a skincluster, it still prints out the "obj, skincluster" rather than the error that it can't find a skinCluster.
I thought a skinCluster returns a string. So if the string is empty, it should print out the error rather than "obj, skincluster".
Any help would be appreciated!
This is a classic Maya issue -- the problem is that Maya frequently wants to give you lists, not single items, even when you know the result ought to be a single item. This means you end up writing a bunch of code to either get one item from a one-item list or to avoid errors that come from trying to get an index into an empty list.
You've got the basics, it's the == "" which is messing you up:
for obj in skinTestList:
objHist = cmds.listHistory(obj, pdo=True)
skinCluster = cmds.ls(objHist, type="skinCluster") or [None]
cluster = skinCluster[0]
print obj, cluster
The or [None] guarantees that you'll always get a list with something in it so it's safe to use the [0] to get the single value. None is a good return value here because (as pointed out in the comments) you can if cluster: and skip empty values.

Asterisk coming up in Jupyter Notebook with a specific code

I am using Jupyter Notebook, I keep getting the asterisk that indicates the kernel is busy when I run this specific code:
var = 2
var += 1
var_rem = var % 3
while var_rem == 0:
var += 2
print var
In order to give some context, I am trying to solve the following exercise:
Define a new number variable and choose a value for it. If the
variable + 1 can be divided by three, increase the variable by two.
Test by printing the final value of the variable and varying the
initial value of that same variable.
I have tried restarting the kernel as it was recommended in front of the asterisk issue but it doesn't work. What is specific about this code that the kernel cannot process it? How do I then solve the exercise?
Note: First post around here, I hope it's relevant.
Your code results in an infinite loop. Your variable var_rem does not change its value in the loop, therefore it runs forever (because it remains 0)
You have to recalculate the while condition within the loop.
Based on the statement your logic is wrong. Try this...
var = 2
if ((var + 1) % 3) == 0:
var +=2
print var
else:
print 'Not divisible by 3'

Categories