繁体   English   中英

libreoffice python 线程睡眠

[英]libreoffice python threading sleep

我想为 libreoffice writer 实现自动保存功能。 我正在使用 python 宏。

这将定期将文档的桌面视图保存回磁盘上的文件,并向桌面发出未修改文档的信号。

这个出色的应用程序套件已经提供了无可争议的出色自动恢复和备份功能,无法满足这一要求。

这是我第一次天真的失败尝试:

def autosave():
    from time import sleep
    doc = XSCRIPTCONTEXT.getDocument()
    args=()
    while True :
        if doc.isModified() :
            doc.storeToURL(doc.getURL(),args)
            doc.setModified(False)
        sleep(60)
        

这样的原因是文件被更新并通知桌面。 问题是睡眠锁定了 UI。

我尝试将计时器放入在后台运行的线程中,然后触发中断——如下所示:

def autosave_timer() :
    while True :
        autosave()
        sleep(60)

def autosave():
    from time import sleep
    doc = XSCRIPTCONTEXT.getDocument()
    args=()
    if doc.isModified() :
            doc.storeToURL(doc.getURL(),args)
            doc.setModified(False)

def run_autosave() :
    thread=Thread(target=autosave_timer)        
    thread.start()
    

这样做的问题是它仅在显式调用run_autosave时运行,而据我了解(显然有缺陷)线程应该连续运行。

是否有明显的小错误或有更好的方法?

我认为问题一定出在其他地方。
如果您从命令行运行lowriter然后手动启动宏,在这种情况下,我将其命名为logger.py并启动 function run_autosave ,它会愉快地循环,保存,不保存或抱怨,直到 LibreOffice 关闭。

显然,这是一项正在进行的工作,需要完善,但基础工作。

from threading import Thread
from time import sleep

def autosave_timer() :
    cnt = 0
    while True :
        cnt += 1
        autosave(cnt)
        sleep(5)

def autosave(cnt):
    doc = XSCRIPTCONTEXT.getDocument()
    url = doc.getURL()
    if not url:
        print("Document is unnamed - Not Saving "+str(cnt))
        return True
    args=()
    if doc.isModified():
        try:
            doc.storeToURL(doc.getURL(),args)
            doc.setModified(False)
            print("Document "+url+" saved "+str(cnt))
        except Exception as e:
            print(str(e))
    else:
        print(url+" Document unchanged "+str(cnt))

def run_autosave():
    thread=Thread(target=autosave_timer)        
    thread.start()

运行为:

$ lowriter
Document is unnamed - Not Saving 1
Document is unnamed - Not Saving 2
Document is unnamed - Not Saving 3
Document is unnamed - Not Saving 4
Document is unnamed - Not Saving 5
Document is unnamed - Not Saving 6
file:///home/rolf/Documents/aaa.odt Document unchanged 7
file:///home/rolf/Documents/aaa.odt Document unchanged 8
file:///home/rolf/Documents/aaa.odt Document unchanged 9
Document file:///home/rolf/Documents/aaa.odt saved 10
file:///home/rolf/Documents/aaa.odt Document unchanged 11
file:///home/rolf/Documents/aaa.odt Document unchanged 12

暂无
暂无

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

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