Breaking out of while True loop
<p>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.</p>

<pre><code>try:
    while True:
        data, addr = s.recvfrom(65507)
        mylist=data.split('\r')
        url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[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
</code></pre>

<p>You open a <code>UDP</code> socket and you use <code>recvfrom</code> to get data from the socket.<br>
You set a high <code>timeout</code> which makes this function a <code>blocking function</code>. 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 <code>timeout</code> reaches. In case of <code>timeout</code> and no data the function will raise an <code>Exception</code>.  </p>

<p>I see two options:</p>

<ul>
<li><p>Send something from the sender that indicates the end of stream (the serial numbers in your case).</p></li>
<li><p>Set a small <code>timeout</code> then catch the <code>Exception</code> and use it to break the loop.  </p></li>
</ul>

<p>Also, take a look at this question: <a href="http://stackoverflow.com/questions/31166594/socket-python-recvfrom">socket python : recvfrom</a></p>

<p>Hope it helps.</p>

python xml while-loop break