Monitor file continuously

From PyMOLWiki
Jump to navigation Jump to search

This script can be used to continuously check the modification timestamp on a file (any format, although this example assumes it's a PDB file), and re-loads it whenever the timestamp changes. As written it is intended to be started from the command line, but this is not a requirement.

The Code

from pymol import cmd
import threading
import time
import os
import sys

class pymol_file_monitor (object) :
  def __init__ (self,
      file_name, 
      time_wait=1) : # time in seconds between mtime check
    self.file_name = file_name
    self.time_wait = time_wait
    self.watch = True # this can be toggled elsewhere to stop updating
    self.mtime = 0
    t = threading.Thread(target=self.check_file)
    t.setDaemon(1)
    t.start()
    print "Watching file %s" % file_name

  def check_file (self) :
    while (self.watch) :
      if (os.path.exists(self.file_name)) :
        print "checking..."
        mtime = os.path.getmtime(self.file_name)
        if (mtime > self.mtime) :
          self.mtime = mtime
          print "Re-loading %s" % self.file_name
          cmd.load(self.file_name, state=1)
      time.sleep(self.time_wait)

if (__name__ == "pymol") :
  monitor = pymol_file_monitor("status.pdb")