Python看门狗在os.system()上永远循环

Python看门狗在os.system()上永远循环,python,python-watchdog,Python,Python Watchdog,我尝试构建一个一次性脚本,在每次更改后自动编译我的latex文档 有关守则: class LatexCompiler(FileSystemEventHandler): def on_modified(self, event): if isinstance(event, watchdog.events.FileModifiedEvent): print event os.system("pdflatex Thesis.tex"

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

有关守则:

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(),就在这里,只打印了一行描述事件的内容


那么到底出了什么问题?

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

我猜,但很可能是
pdflatex
创建了中间文件,然后进行修改。或者可能只是输出pdf文件存在于上一次运行中,然后由
pdflatex
修改。无论哪种方式,这都会触发\u modified()上的
处理程序,该处理程序反过来再次运行
pdflatex
(修改文件),从而触发对\u 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()

你有没有试着用类似模块的东西打“pdflatex Thesis.tex”电话?只是提到因为os.system被子进程取代了是的,我做了,它没有区别什么是
Observer
?这是什么库/模块?watchdog,请参阅:您对pdflatex创建中间文件的猜测是正确的,该文件会在_modified()上反复触发。非常感谢您提供正确详细的答案/解决方案。