#!/usr/bin/python
#
# Example script to get the length of a remote file via HTTP
# without downloading the whole file; quick and dirty =)
#
# Thomas Perl <thpinfo.com>, 2007-12-10
#

import httplib
import urlparse

def url2length(url):
    (scheme, netloc, path, parms, qry, fragid) = urlparse.urlparse(url)
    conn = httplib.HTTPConnection(netloc)
    start = len(scheme) + len('://') + len(netloc)
    conn.request('HEAD', url[start:])
    r = conn.getresponse()
    if 'content-length' in r.msg:
        return int(r.msg['content-length'])
    else:
        return None

if __name__ == '__main__':
    import sys
    if len(sys.argv) < 2:
        print 'Usage: %s http://example.com/bla.mp3' % sys.argv[0]
        sys.exit(1)
    print 'The length of this file: ' + str(url2length(sys.argv[-1]))

