Python线程和shutil不能携手合作?

时间:2014-07-08 01:51:33

标签: python multithreading shutil

我正在尝试创建一个python脚本,将文件从远程服务器复制到本地驱动器。问题是我注意到它没有产生一个线程来并行复制其他文件。

import shutil
import threading

LocalPath = "C:\\folder1"
RemotePath = "X:\\folder1"

# downloader/copier
def monitorCopy (Filename) :
    print("Copying of "+Filename+" started.")
    shutil.copy(RemotePath+"\\"+Filename+"\\"+Filename+".zip",LocalPath)
    print("Copying of "+Filename+" finished.")

# main function
if __name__ == "__main__" :
    filelist = ["file1","file2","file3"]
    print(range(len(filelist)))
    p = []
    for i in range(len(filelist)) :
        p.append(i)
        p[i] = threading.Thread(target=monitorCopy,args=(filelist[i],))
        p[i].daemon = True
        p[i].start()
        p[i].join() 

文件夹树看起来像这样:

Remote Repository
     [+] --- Filename
                [+] --- Filename.zip

Local Repository
     [+] --- Filename.zip

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

您在创建每个线程对象后立即调用join,这阻止了一次运行多个线程。 thread_object.join()调用告诉Python阻塞直到thread_object完成执行,在你的情况下意味着你​​正在为filelist中的项启动一个线程,阻塞直到线程完成,然后移动转到filelist中的下一个项目并执行相同的操作。你真正想做的是并行创建所有线程,并且在创建它们之后只创建join个:

if __name__ == "__main__" :
    filelist = ["file1","file2","file3"]
    print(range(len(filelist)))
    p = []
    for f in filelist:
        t = threading.Thread(target=monitorCopy,args=(f,))
        p.append(t)
        t.daemon = True
        t.start()

    for t in p:
        t.join()