chowpay chowpay - 17 days ago 4x
Python Question

Not sure why my python output is looping

I wrote a little bit of code to read a number in a file. Append it to a variable, then increment the number so the next time it runs the number in the file will be number +1. It looks like its working except it seems to increment twice.. For example here is my code :

11 def mcIPNumber():
12 with open('mcIPlatest.txt', 'r+') as file:
13 NameNumber='\n','')
14 NameNumber=int(NameNumber)
15 NewNumber= NameNumber+1
16 print "newnumber = %s" % NewNumber
18 file.write(str(NewNumber))
19 file.truncate()
20 return NameNumber
22 def makeNameMCTag():
23 NameNumber = mcIPNumber()
24 NameTag = "varName" + str(NameNumber)
25 print "Name Tag: %s" % NameTag
26 mcGroup = "varTagmc"
27 #IPNumber = 1
28 mcIP = "172.16.0.%s" % NameNumber
29 print ( "Multicast Tag: %s, %s" % (mcGroup,mcIP))
32 mcIPNumber()
33 makeNameMCTag()

But here is my output.. notice that "NewNumber" gets printed out twice.. for some reason"

newnumber = 2
newnumber = 3
Name Tag: varName2
Multicast Tag: varTagmc,

So it correctly made my varName2 and my IP (incremented my initial number in the file by 1) but this means the 2nd time I run it.. I get this:

newnumber = 4
newnumber = 5
Name Tag: varName
Multicast Tag: varTagmc,

My expected result is this:

newnumber = 3
Name Tag: varName3
Multicast Tag: varTagmc,

Any idea why its looping?


(by the way if you're curious I'm trying to write some code which will eventually write the tf file for my TerraForm lab)


Because of this:

 def makeNameMCTag():
     NameNumber = mcIPNumber()

You are calling mcIPNumber from inside makeNameMCTag, so you don't excplicitly need to call that method in line 32.


def make_name_mc_tag(name_number):
    NameTag = "varName" + str(name_number)
    print "Name Tag: %s" % NameTag


here you are passing the required data as a parameter.