문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top