1

I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that the program will exit after writing all the serial numbers.

try:
    while True:
        data, addr = s.recvfrom(65507)
        mylist=data.split('\r')
        url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', data)
        print url[0]
        response = urllib2.urlopen(url[0])
        the_page = response.read()

        tree = ET.XML(the_page)
        with open("temp.xml", "w") as f:
            f.write(ET.tostring(tree))

        document = parse('temp.xml')
        actors = document.getElementsByTagName("ns0:serialNumber")
        for act in actors:
            for node in act.childNodes:
                if node.nodeType == node.TEXT_NODE:
                        r = "{}".format(node.data)
                        print r
                        logToFile(str(r))

time.sleep(10)
        s.sendto(msg, ('239.255.255.250', 1900) )

except socket.timeout:
    pass
Krishna Prasad
  • 71
  • 1
  • 4
  • 13

3 Answers3

1

I would normally create a flag so that the while would be

while working == True:

Then reset the flag at the appropriate time.

This allows you to use the else statement to close the text file and output the final results after the while loop is complete. Else clause on Python while statement.

Note that it is always better to explicitly close open files when finished rather than relying on garbage collection. You should also close the file and output a timeout message in the except logic.

For debugging, you can output a statement at each write to the text file.

Community
  • 1
  • 1
sabbahillel
  • 4,357
  • 1
  • 19
  • 36
0

If your s.recvfrom(65507) is working correctly it should be an easy fix. Write this code just below your data, addr = s.recvfrom(65507)

if not data:
    break
Bishwas Mishra
  • 1,235
  • 1
  • 12
  • 25
0

You open a UDP socket and you use recvfrom to get data from the socket.
You set a high timeout which makes this function a blocking function. It means when you start listening on the socket, if no data have been sent from the sender your program will be blocked on that line until either the sender sends something or the timeout reaches. In case of timeout and no data the function will raise an Exception.

I see two options:

  • Send something from the sender that indicates the end of stream (the serial numbers in your case).

  • Set a small timeout then catch the Exception and use it to break the loop.

Also, take a look at this question: socket python : recvfrom

Hope it helps.

Community
  • 1
  • 1
Ahmad Siavashi
  • 979
  • 1
  • 12
  • 29