文件复制功能将不会在计时器功能中运行

时间:2019-05-17 09:44:59

标签: python python-3.x shutil file-copying

我想创建一个函数,将给定目录中的每个文件复制给定的秒数。我有一个有效的文件复制功能,以及一个计时器功能,该功能可以在一定秒数后停止脚本。但是,我只能让任何一个工作,而不能像我的预期那样工作。我的上一次尝试导致我将文件复制功能放置在计时器功能中,该功能允许计时器正常工作,但文件复制功能将无法运行。

#------------------------------------------------------
# Treading classes
class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

#----------------------------------------------------
# Copying files


def hello(name):
    print ("copying %s!" % name)
src = #path
dest = #dest_path
print ("starting...")
rt = RepeatedTimer(1, hello, "files") # it auto-starts, no need of rt.start()
try:
    sleep(time1)
    def recursive_copy(src, dest):

        for item in os.listdir(src):
            file_path = os.path.join(src, item)

            # if item is a file, copy it
            if file_path.endswith('.txt') or file_path.endswith('.pdf') or file_path.endswith('.csv') or file_path.endswith('.pptx') or file_path.endswith('.xlsx') or file_path.endswith('.docx') or file_path.endswith('.ppt') or file_path.endswith('.xls') or file_path.endswith('.html') or file_path.endswith('.doc') or file_path.endswith('.html') or file_path.endswith('.doc'):

            #if os.path.isfile(file_path):
                shutil.copy(file_path, dest)

            # else if item is a folder, recurse 
            elif os.path.isdir(file_path):
                new_dest = os.path.join(dest, item)
                os.mkdir(new_dest)
                recursive_copy(file_path, new_dest)
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

0 个答案:

没有答案