python实践 - 下载文件

单线程.慢慢补充扩展

你要做的就是将文件路径加入到listfile列表中,哦还有,文件下载路径,这里为d:/tmp

#coding:utf-8
import httplib
import threading
import time
import os

class download(threading.Thread):
    
def __init__ (self,threadname,downfile):
        self.filename 
= str(downfile).split('/')[-1]
        self.domainname 
= str(downfile.split('//')[-1]).split('/')[0]
        self.file 
= downfile[downfile.index(self.domainname)+len(self.domainname):]
        threading.Thread.
__init__(self,name=threadname)
    
def run(self):
        conn 
= httplib.HTTPConnection(self.domainname)
        conn.putrequest(
'GET',self.file)
        conn.putheader(
'Referer','http://'+self.domainname)
        conn.endheaders()
        rMsg 
= conn.getresponse()
        fwrite 
= open(os.path.join('d:/tmp/',self.filename),'wb+')
        
print "start downloading"
        ftmp 
= rMsg.read(1000)
        
while len(ftmp):
          fwrite.write(ftmp)
          ftmp 
= rMsg.read(1000)
        
print "Done!\b\b\n",
        fwrite.close()
        conn.close()

#建立并启动线程
listfile = [
'http://www.scriptlover.com/wish/style/spring/C0FFE51.gif',
]
for file in listfile:
  downThread 
= download("downThread",file)
  downThread.start()

posted @ 2009-04-29 16:31  ________囧丶殇  阅读(340)  评论(0编辑  收藏  举报