如何simultaneusly从FTP Python中下载一些文件(How to download

2019-08-31 17:35发布

我在Python编程新手。 我的问题是,如何在同一时间下载了一些文件。 不是文件,而是同时从一个目录上的FTP文件。 现在,我使用这个脚本,但我不知道我怎么能重建这样的代码:

  filenames = []
    ftp.retrlines("NLST", filenames.append)
    print filenames
    print path
    for filename in filenames:
        local_filename = filename
        print filename
        print local_filename
        f = open(local_filename, "wb") 

        s = ftp.size(local_filename)     
        sMB = s/(1024*1024) 
        print "file name: " + local_filename + "\nfile size: " + str(sMB) + " MB" 
        ftp.retrbinary("RETR %s" % local_filename, f.write) 
    print "\n Done :) "
    time.sleep(2)
    f.close()
    ftp.quit() #closing connection
    time.sleep(5)

它工作正常,但不是我所需要的。

Answer 1:

您可以使用多个线程或进程。 请确保您创建一个新的ftplib.FTP在每个线程对象。 最简单的方法(代码明智)是使用multiprocessing.Pool

#!/usr/bin/env python
from multiprocessing.dummy import Pool # use threads
try:
    from urllib import urlretrieve
except ImportError: # Python 3
    from urllib.request import urlretrieve

def download(url):
    url = url.strip()
    try:
        return urlretrieve(url, url2filename(url)), None
    except Exception as e:
        return None, e

if __name__ == "__main__":
   p = Pool(20) # specify number of concurrent downloads
   print(p.map(download, open('urls'))) # perform parallel downloads

其中urls包含FTP网址,要下载的文件如ftp://example.com/path/to/fileurl2filename()中提取的文件名部分从URL例如:

import os
import posixpath
try:
    from urlparse import urlsplit
    from urllib import unquote
except ImportError: # Python 3
    from urllib.parse import urlsplit, unquote

def url2filename(url, encoding='utf-8'):
    """Return basename corresponding to url.

    >>> print url2filename('http://example.com/path/to/dir%2Ffile%C3%80?opt=1')
    fileÀ
    """
    urlpath = urlsplit(url).path 
    basename = posixpath.basename(unquote(urlpath))
    if os.path.basename(basename) != basename:
        raise ValueError(url)  # reject 'dir%5Cbasename.ext' on Windows
    return basename


文章来源: How to download a few files simultaneusly from ftp in Python