[Ilugc] [TIP] Python script of 23 lines to download file using http

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Fri, 18 Nov 2011 07:47:40 +0530

$ cat htdl.py
#!/usr/local/bin/python
import httplib,os,sys

if len(sys.argv) < 2:
        print "Please give the URL to download from!\n"
        sys.exit()
url=sys.argv[1]
vals = url.split('/')
host =vals[2]
filename = vals[len(vals) -1]
path = '/'  + '/'.join(vals[3:])
print "Connecting to ", host
conn = httplib.HTTPConnection(host)
print "Connected"
conn.request("GET",  path)
r = conn.getresponse()
print "Getting file, wait..."
data = r.read()
conn.close()
f = open(filename, 'w')
f.write(data)
f.close()
print "File written to " , filename


Download:

ftp://tulip.pye.org/htdl.py

HTML

ftp://tulip.pye.org/htdl.py.html

This is very short code and also very different from the C and perl
versions past.

Partly due to the fact that we use httplib module but I think it has
also got to
 do with python's elegance.

Let me do a code walk thro'.

Lines 8 to 11 deal with using split() to obtain relevant tokens.

Unlike the perl and C versions we don't get to know live feedback and print of
 how many bytes were read from the network.

Moreover python slurps the whole file from network into a huge data buffer and
 then writes to a file at one stroke. So it is all or nothing.

If you press Ctrl-C when the script is running you get nothing.

But in the perl and C case you get a half filled file.

Though I am not a python geek this proves python's elegance in a small way.

-Girish

-- 
G3 Tech
Networking appliance company
web: http://g3tech.in ?mail: girish at g3tech.in

Other related posts: