在 Python 中有没有办法中断 shutil copytree 操作?

Is there a way to interrupt shutil copytree operation in Python?

总的来说,我对编程还很陌生。我需要开发一个程序,它可以一次复制多个目录,并且还要考虑到多个文件类型的异常。我遇到了提供 copytree 和 ignore_patterns 功能的 shutil 模块。这是我的代码片段,它也使用了 wxPython 多目录对话框:

import os
import wx
import wx.lib.agw.multidirdialog as MDD
from shutil import copytree
from shutil import ignore_patterns

app = wx.App(0)
dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(),  agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST)

dest = "Destination Path"

if dlg.ShowModal() != wx.ID_OK:
    dlg.Destroy()

paths = dlg.GetPaths()

ext = ['*.tiff', '*.raw', '*.p4p', '*.hkl', '*.xlsx']

for path in enumerate(paths):
    directory = path[1].replace('Local Disk (C:)','C:')
    copytree(directory, dest, ignore=ignore_patterns(directory, *ext))

dlg.Destroy()
app.MainLoop()

这段代码对我来说效果很好。有时,我会复制数 TB 的数据。无论如何, shutil.copytree 可以被打断吗?我问这个,因为我第一次 运行 这个程序时,我选择了一个相当大的目录并无意中复制了大量文件(成功!)并且想停止它 :( 。一旦我解决了这个问题,我终于开始使用 GUI 了!如果我能提供更多信息,请告诉我!在此先感谢您提供的所有帮助!

您可以使用 multiprocessing 模块 运行 在单独的 python 进程中复制。代码可能如下所示:

import time
import shutil
from multiprocessing import Process


def cp(src: str, dest: str):
    shutil.copytree(src, dest)


if __name__ == '__main__':
    proc = Process(target=cp, args=('Downloads', 'Tmp'), daemon=True)
    proc.start()
    time.sleep(3)
    proc.terminate()

在我的示例中,主进程启动了一个子进程,该子进程进行实际处理,并在 3 秒后终止它。您还可以通过调用进程的 is_alive() 方法来检查进程是否 运行ning。

copytree 接受 copy_function 作为参数。如果您传递一个检查标志的函数,您可能会引发错误以中断操作。

from shutil import copytree, copy2

# set this flag to True to interrupt a copytree operation
interrupt = False


class Interrupt(Exception):
    """ interrupts the copy operation """


def interruptable_copy(*args, **kwargs):
    if interrupt:
        raise Interrupt("Interrupting copy operation")
    return copy2(*args, **kwargs)


copytree(src, dst, copy_function=interruptable_copy)