chowpay chowpay - 2 months ago 6
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= file.read().replace('\n','')
14 NameNumber=int(NameNumber)
15 NewNumber= NameNumber+1
16 print "newnumber = %s" % NewNumber
17 file.seek(0)
18 file.write(str(NewNumber))
19 file.truncate()
20 return NameNumber
21
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))
30
31
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, 172.16.0.2


So it correctly made my varName2 and my IP 172.16.0.2 (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, 172.16.0.4


My expected result is this:

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


Any idea why its looping?

Thanks!

(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)

Answer

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.

Alternatively

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

make_name_mc_tag(mcIPNumber())

here you are passing the required data as a parameter.