我同时使用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)我已经考虑过添加另一个except语句和一个time.sleep(5),以帮助减少重叠的进程。或者简单地删除os.unlink(FILE)行。,处理这种错误的最佳方法是什么?
发布于 2017-03-09 15:47:26
我知道这篇文章有3年的历史,但是为了其他用户的利益,我会在你的代码中给出一个可能的解决方案--我没有看到你在操作后关闭你的文件,所以我认为这就是问题所在。作为一种最佳实践,使用with语句总是很好的,因为它提供了上下文管理器和更好的错误处理。
因此,您检索文件的代码部分应该如下所示
with open(FILE, 'wb') as fhandle:
ftp.retrbinary('RETR ' + FILE, fhandle.write)这应该能解决你的问题。你不需要os.unlink(FILE)
如果您需要一些关于with语句的背景信息,这里是访问PEP 343 -- "with“语句的地方。
发布于 2014-02-18 14:45:13
我想说的是,问题在于如何启动会话并允许它们重叠文件。尝试在一个主会话中运行它们,并传递文件作为参数下载。
或者您可以只使用多处理模块,这可能更容易。
我猜在paraller下载多个文件时,不应该有两个进程在同一个文件上运行的情况(只要您不以更并行的方式下载一个文件)。
https://stackoverflow.com/questions/21856383
复制相似问题