python实现Linux命令wget

2020-01-07 16:34:16 浏览数 (2)

代码语言:javascript复制
#!/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

0 人点赞