Monitor file continuously

From PyMOLWiki
Revision as of 18:00, 23 January 2012 by Natechols (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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")