Search code examples
pythonpycurl

getting the file size with pycurl


I want to write a downloader with Python and I use PycURL as my library, but I have a problem. I can't get the size of the file which I want to download. Here is part of my code:

import pycurl
url = 'http://www.google.com'
c = pycurl.Curl()
c.setopt(c.URL, url)
print c.getinfo(c.CONTENT_LENGTH_DOWNLOAD)
c.perform()

When I test this code in Python shell, it's ok but when I write it as a function and run it, it gives me -1 instead of the size. What is the problem?

(code has been edited)


Solution

  • From the pycurl documentation on the Curl object:

    The getinfo method should not be called unless perform has been called and finished.

    You're calling getinfo before you've called perform.

    Here is a simplified version of your example, does this work?

    import pycurl
    
    url = 'http://www.google.com'
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.perform()
    print c.getinfo(c.CONTENT_LENGTH_DOWNLOAD)
    

    You should see the HTML content followed by the size.