python 单个函数实现多线程

需求:将一个文件夹中的所有图片复制进word文档中
进度:已经实现复制函数,单线程已经跑通实现
实现效果:文件夹中的几十张图片通过多线程实现同时复制进word
要求:在源代码中修改多线程部分


```python

from docx import Document
from docx.shared import Inches
import os
from PIL import Image
import threading



def pic_to_word():
    #图片所在文件夹路径
    folder="D:\\shu_pic_srrc"
    for root, dirs, pics in os.walk(folder):
        doc=Document()
        for i in range(0,len(pics)):
            filepath = 'D:\\shu_pic_srrc\\'+pics[i]

            try:
                doc.add_picture(filepath,width=Inches(6),height=Inches(4))
            except Exception:
                pic_tmp=Image.open(filepath)

                pic_tmp.save(pic_tmp)

                doc.add_picture(filepath, width=Inches(6),height=Inches(4))
            doc.save('D:\\shu_pic_srrc\\shu_pic_srrc.docx')
            print("pic", i + 1, "successfully added.")


if __name__ == '__main__':
    threads = []
    folder = "D:\\shu_pic_srrc"
    for root, dirs, pics in os.walk(folder):
        for i in range(0, len(pics)):
            threads.append(threading.Thread(target=pic_to_word))

    for thread in threads:
        thread.start()

```

将函数里的遍历文件夹的循环去掉,改写一下if__name__里的语句,将如下代码路径改成你的文档路径即可:

import threading
from PIL import Image
import os
from docx.shared import Inches
from docx import Document

def pic_to_word(pics):
    doc = Document()
    for i in range(0, len(pics)):
        filepath = r"F:\2021\qa\ot1\imgs\test_thread"+"/"+pics[i]
        try:
            doc.add_picture(filepath, width=Inches(6), height=Inches(4))
        except Exception:
            pic_tmp = Image.open(filepath)
            pic_tmp.save(pic_tmp)
            doc.add_picture(filepath, width=Inches(6), height=Inches(4))
        doc.save(r"F:\2021\qa\ot1\imgs\test_thread\shu_pic_srrc.docx")
        print("pic", i + 1, "successfully added.")


if __name__ == '__main__':
    threads = []
    folder = r"F:\2021\qa\ot1\imgs\test_thread"
    for root, dirs, pics in os.walk(folder):
        threads.append(threading.Thread(target=pic_to_word,args=[pics]))
    for thread in threads:
        thread.start()