如果给出网络错误,请在Python中重试拷贝尊重?

发布于 2025-02-05 19:08:28 字数 1116 浏览 2 评论 0原文

我目前正在尝试创建一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文