【问题标题】:Handling parallel ftp download errors处理并行 ftp 下载错误
【发布时间】:2014-02-18 14:12:54
【问题描述】:

我正在使用 Python 的多个会话同时从 ftp 服务器下载多个文件。在某些时候,一个会话(我怀疑)读取了另一个进程正在访问的文件并引发以下错误:

Traceback (most recent call last):   File
"F:\utilities\python\downloadFTP_NV.py", line 66, in <module>
     os.unlink(FILE) WindowsError: [Error 32] The process cannot access the file because it is being used by another process:
u'm_4011851_ne_11_1_20100620.tif'

这是我似乎无法找到处理错误并移至下一个要下载的文件的最佳方法的代码块:

        # Set logic so that already downloaded or partially
        # downloaded files will not be downloaded again
        if os.path.exists(fileCheck): # "fileCheck" is a file prior to renaming
            print 'File "%s" exists already' % name
            pass

        elif os.path.exists(fileCheck2): # "fileCheck2 is a file after renaming
            print 'File "%s" exists already' % FILE
            pass

        else:
            try:
                f.cwd(DIRN + folder)
                start = time.clock()
                f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
                end = time.clock()
                arcpy.Rename_management(os.path.join(workspace, FILE), os.path.join(workspace, name))
            except ftplib.error_perm:
                print 'ERROR: cannot read file "%s"' % FILE
                os.unlink(FILE)

我考虑过添加另一个带有time.sleep(5)except 语句,以帮助减少重叠进程。或者可能只是删除os.unlink(FILE) 行。 处理此类错误的最佳方法是什么?

【问题讨论】:

    标签: python error-handling ftp ftplib


    【解决方案1】:

    我知道这篇文章已经 3 年了,但是为了其他用户可能有同样的问题,我会给出一个可能的解决方案 在您的代码中,我没有看到您在操作后关闭了文件,所以我认为这就是问题所在。作为最佳实践,最好使用 with 语句,因为它提供了上下文管理器和更好的错误处理。

    所以你检索文件的部分代码应该是这样的

    with open(FILE, 'wb') as fhandle:
          ftp.retrbinary('RETR ' + FILE, fhandle.write)
    

    这应该可以解决您的问题。而且你不需要os.unlink(FILE)

    如果您需要有关with 声明的一些背景信息,请访问PEP 343 -- The "with" Statement

    【讨论】:

      【解决方案2】:

      我会说问题在于您如何启动会话并允许它们重叠文件。尝试在一个主会话中运行它们并将文件作为参数传递给下载。

      或者您可以使用multiprocessing 模块,这可能更容易。

      我猜在并行下载多个文件的过程中,您不应该遇到两个进程试图对同一个文件进行操作的情况(只要您不以并行方式下载一个文件)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 2017-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多