Question

I have a function:

def getXMLpayload(server):
    try:
        result = urllib2.urlopen('http://%s' % server, None, 15)
    except urllib2.URLError:
        return 'unknown'
    except:
        raise Exception('Unexpected response from server')
    return result

I want it to return a urllib2 object so that in another function I can call the above function and then use its output like so:

xmlPayload = result.read()
    tree = ET.ElementTree(ET.fromstring(xmlPayload))
    root = tree.getroot()

I think it is currently returning a string instead, how would I get it to return a file-like object, namely what is returned by urllib2.urlopen?

Was it helpful?

Solution

Your function is not returning a string, but a file-like object.

If it were a string indeed, result.read() would raise an Error, because strings don't have a method read.

Once read, xmlPayload is a string which you can then pass to ET.fromstring.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top