有没有一种方法可以中断Python中的shutdownil copytree操作?

时间:2018-12-17 12:47:13

标签: python python-3.x wxpython shutil copytree

我一般对编程还是比较陌生的。我需要开发一个程序,该程序可以一次复制多个目录,同时还要考虑多个文件类型异常。我遇到了Shutil模块,该模块提供了copytree和ignore_patterns函数。这是我的代码的片段,它也使用了wxPython Multiple Directory对话框:

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上!如果我可以提供更多信息,请让我知道!在此先感谢您的所有帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用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()方法来检查该流程是否正在运行。

答案 1 :(得分:0)

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)
相关问题