简体   繁体   English

Python UNO和线程

[英]Python UNO and Threads

I am working with Python UNO using the "internal" (Libreoffice is the host process) version where the Python interpreter lives within Libreoffice/Openoffice. 我正在使用“内部”(Libreoffice是宿主进程)版本的Python UNO,其中Python解释器位于Libreoffice / Openoffice中。 I would like to make the code nonblocking...that is once the code gets called as a macro, it starts a second thread and returns the main thread back to Office so that it does not block the UI while it continues to run a very lengthy process (10-20 minutes execution time). 我想使代码成为非阻塞性的...也就是说,一旦代码被调用为宏,它将启动第二个线程并将主线程返回给Office,这样它就不会在继续运行用户界面时阻塞UI。漫长的过程(10-20分钟的执行时间)。

When I tried exactly this, LibreOffice freezes forever. 当我尝试这样做时,LibreOffice会永久冻结。 I've searched just about everywhere but other than an odd reference to importing scipy in a second thread and then blocking while waiting on that thread (myrhread.join()), there seems to be nowhere that this is done. 除了在第二个线程中导入scipy然后在等待该线程时阻塞(myrhread.join())的奇怪参考之外,我几乎在所有地方都进行了搜索,似乎无处不在。

Alternatively, is it possible to create a new ServiceManager so that I could invoke a second process and then link back to the ServiceManager so that I can return back to LibreOffice in the normal way without locking it up with a "ghost thread"? 或者,是否可以创建一个新的ServiceManager,以便我可以调用第二个进程,然后链接回ServiceManager,这样我就可以以正常方式返回LibreOffice,而无需使用“鬼线程”将其锁定?

After a lot of digging, I found the answer here: 经过大量的挖掘,我在这里找到了答案:

LibreOfficeForum Threading Example LibreOfficeForum线程示例

For simple long-running tasks where it would otherwise block the UI thread, this works very well. 对于可能会阻塞UI线程的简单长时间运行的任务,此方法效果很好。 The relevant code is as follows: 相关代码如下:

from threading import Thread
from time import sleep
import uno

t = None

def test_worker(doc):

    # Wait 30 seconds for demonstration purposes
    sleep(30)

    # Get the 1st sheet in the document and insert text into cell A1
    doc.Sheets.getByIndex(0).getCellByPosition(0,0).String = "I'm back"

def delayedRun(*args):
    global t
    doc = XSCRIPTCONTEXT.getDocument()
    t = Thread(target = test_worker, args = (doc,))
    t.start()

g_exportedScript = delayedRun,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM