如果给出网络错误,请在Python中重试拷贝尊重?
我目前正在尝试创建一个Python脚本。其中一个步骤是,它应创建一个文件夹的副本,包括子文件夹,并事先检查文件夹是否已经存在。如果是,则应首先删除文件夹。不幸的是,该文件夹很大,而且我大部分时间都在网络错误上运行。因此,任务停在中间,我必须手动重新启动脚本。我如何实现重试。如果未能在文件夹中删除或复制文件,则应以一定的数量重试。
当前的功能定义非常直截了当:
def copy_directory(root_directory, target_directory):
import shutil
import os
if os.path.isdir(target_directory) == True:
shutil.rmtree(target_directory)
shutil.copytree(root_directory, target_directory)
else:
shutil.copytree(root_directory, target_directory)
copy_directory(path_folderA, path_folderAcopy)
搜索后,我正在考虑实现STH。像这样的删除任务:
def copy_directory(root_directory, target_directory):
import shutil
import os
if os.path.isdir(target_directory) == True:
while True:
try:
shutil.rmtree(target_directory)
except:
continue
break
shutil.copytree(root_directory, target_directory)
else:
shutil.copytree(root_directory, target_directory)
这项工作会和复制任务呢?实施此功能有更好的选择吗?
谢谢!
I'm currently trying to create a python script. One of the steps is that it shall create a copy of a folder, including subfolders, and checks beforehand if the folder already exists. If yes, then it should delete the folder first. Unfortunately, the folder is quite big and I'm running on network errors most of the time. Therefore, the task stops in the middle and I have to manually restart the script. How can I implement a retry. If it fails to delete or copy a file in the folder, it should retry for a certain amount.
The current function definition is quite straight forward like this:
def copy_directory(root_directory, target_directory):
import shutil
import os
if os.path.isdir(target_directory) == True:
shutil.rmtree(target_directory)
shutil.copytree(root_directory, target_directory)
else:
shutil.copytree(root_directory, target_directory)
copy_directory(path_folderA, path_folderAcopy)
After searching I'm thinking to implement sth. like this for the removal task:
def copy_directory(root_directory, target_directory):
import shutil
import os
if os.path.isdir(target_directory) == True:
while True:
try:
shutil.rmtree(target_directory)
except:
continue
break
shutil.copytree(root_directory, target_directory)
else:
shutil.copytree(root_directory, target_directory)
Would this work and what about the copy task then? Are there better options in implementing this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论