1

我尝试构建一个一次性脚本,在每次更改后自动编译我的乳胶文档。

相关代码:

class LatexCompiler(FileSystemEventHandler):
    def on_modified(self, event):
        if isinstance(event, watchdog.events.FileModifiedEvent):
            print event
            os.system("pdflatex Thesis.tex")

if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else '.'

    os.chdir("/path/to/my/tex/file")
    observer = Observer()
    observer.schedule(LatexCompiler(), path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

一旦我添加了 os.system(...) 行, on_modified() 方法就会在触发后开始永远循环。为了确保仅在我省略了对 os.system() 的调用后才调用 on_modified() 并且它就在那里,只打印了一行描述事件。

那么出了什么问题呢?

4

1 回答 1

2

每当修改受监视目录中的任何on_modified()现有文件时,都会调用事件处理程序。

我猜,但它很可能会pdflatex创建中间文件,然后对其进行修改。或者可能只是输出 pdf 文件存在于以前的运行中,然后由pdflatex. 无论哪种方式,这都会触发on_modified()处理程序,该处理程序又会pdflatex再次运行(修改文件),这会触发另一个对on_modified().... 的调用。你明白了。

您可以监视一组特定的文件,即您的输入 tex 文件,然后pdflatex仅在其中一个文件被修改时触发。有一些细节需要清理,但下面应该会给你一个想法。

import os, time, sys
import watchdog.events
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer


class LatexCompiler(FileSystemEventHandler):
    def __init__(self, files, *args, **kwargs):
        super(LatexCompiler, self).__init__(*args, **kwargs)
        self._files = files
        print "LatexCompiler(): monitoring files %r" % self._files

    def on_modified(self, event):
        if (isinstance(event, watchdog.events.FileModifiedEvent) and
                event.src_path in self._files):
            print event
            os.system("pdflatex %s" % event.src_path)

if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else '.'

    observer = Observer()
    files = [os.path.join(path, f) for f in ['Thesis.tex', 'Resume.tex']]
    observer.schedule(LatexCompiler(files), path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
于 2014-07-29T13:15:15.020 回答