python实现Linux命令wget

发布时间:2019-09-15 10:01:33编辑:auto阅读(2006)

    #!/bin/python
    #coding:utf-8
    def wget(url,new_name=""):
        '''
        wget封装,需提供下载地址,新文件名参数可省略
        '''
        try:
            file_name = url[url.rfind("/")+1:]
            if new_name == "":
                new_name = file_name
            fp = urllib.urlopen(url)
            py_ver = sys.version[:3]
            if fp.getcode() != 200:
                raise NameError,'%s not exist.'%file_name
                         
            buf_len = 2048
            f = open(new_name,'wb')
            size = 0
            while 1:
                s = fp.read(buf_len)
                if not s:
                    break
                f.write(s)
                size += len(s)
            fp.close()
            f.flose()
            print "%s success"%url
        except Exception,e:
            print Exception,":",e


关键字