多线程和多进程

Added in version 0.13.0.

多线程

虽然xlwings在技术上并不是线程安全的,但是用在线程中也很便利,只要版本在v0.13.0以上并且遵循一个简单的规则:不要把xlwings对象传递给线程。在macOS中,这个规则不是硬性要求,但是如果你希望自己的程序能够跨平台,也还是建议遵循。

请考虑下面 无法 正常工作的例子:

import threading
from queue import Queue
import xlwings as xw

num_threads = 4


def write_to_workbook():
    while True:
        myrange = q.get()
        myrange.value = myrange.address
        print(myrange.address)
        q.task_done()


q = Queue()

for i in range(num_threads):
    t = threading.Thread(target=write_to_workbook)
    t.daemon = True
    t.start()

for cell in ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10']:
    # THIS DOESN'T WORK - passing xlwings objects to threads will fail!
    myrange = xw.Book('Book1.xlsx').sheets[0].range(cell)
    q.put(myrange)

q.join()

为了让上面的代码正常工作,仅需要把传递给线程的 Book 对象改为一个完全限定的单元格引用:

import threading
from queue import Queue
import xlwings as xw

num_threads = 4


def write_to_workbook():
    while True:
        cell_ = q.get()
        xw.Book('Book1.xlsx').sheets[0].range(cell_).value = cell_
        print(cell_)
        q.task_done()


q = Queue()

for i in range(num_threads):
    t = threading.Thread(target=write_to_workbook)
    t.daemon = True
    t.start()

for cell in ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10']:
    q.put(cell)

q.join()

多进程

备注

Multiprocessing is only supported on Windows!

多进程要遵循的规则和多线程的一样,下面是可行的例子:

from multiprocessing import Pool
import xlwings as xw


def write_to_workbook(cell):
    xw.Book('Book1.xlsx').sheets[0].range(cell).value = cell
    print(cell)


if __name__ == '__main__':
    with Pool(4) as p:
        p.map(write_to_workbook,
              ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10'])