我正在尝试创建一个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
有人可以帮我这个吗?
答案 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()