Commits

Anonymous committed 640362f

added "get_args" and "update_at_intervals" functions

  • Participants
  • Parent commits 0acd94d

Comments (0)

Files changed (1)

File check_for_updated_file/updater.py

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import optparse, os, sys, time
+from subprocess import Popen, PIPE
+
+def get_args():
+    usage = "usage: %prog [options] command"
+    parser = optparse.OptionParser(usage)
+    parser.add_option('-c', '--check', dest = 'check',
+                      default = 2, type = 'int', metavar = 'SECOND',
+                      help = 'check at intervals(second)')
+    parser.add_option('-u', '--update', dest = 'update',
+                      default = None, type = 'int', metavar = 'SECOND',
+                      help = 'update at regular intervals(second), '
+                             'have a priority over "check" option')
+    parser.add_option('-v', '--verbose',    dest = 'verbose', 
+                      action = 'store_true', default = False,
+                      help = 'print debug messages to stdout')
+    
+    opts, args = parser.parse_args()
+    if args:
+        return opts, args
+    else:
+        parser.print_help()
+        sys.exit(0)
+
+def run_command(command, verbose):
+    local_time = time.localtime()
+    p = Popen(command, stdout=PIPE, stderr=PIPE)
+    p.wait()
+    status = p.returncode
+    stdout, stderr = p.communicate()
+    cmd_str = ' '.join(command)
+    if verbose:
+        print time.strftime('\n== run at %Y/%m/%d %H:%M:%S', local_time)
+        print '== %s\n%s' % (cmd_str, stdout)
+        print time.strftime('\n== complete at %Y/%m/%d %H:%M:%S'), '(status: %d, %.1f secs)' % (status, time.time() - time.mktime(local_time))
+    
+    if status != 0:
+        print '== error %s\n%d: %s' % (cmd_str, status, stderr)
+
+def update_at_intervals(args, opts):
+    while True:
+        run_command(args, opts.verbose)
+        time.sleep(opts.update)
+
+def check_at_intervals(args, opts):
+    checked_at = time.time()
+    while True:
+        filelist = []
+        for dirname, dirs, files in os.walk('.'):
+            for f in files:
+                filelist.append(os.path.join(dirname, f))
+        lasts = reversed(sorted(os.stat(f).st_mtime for f in filelist))
+        newest = lasts.next()
+        if newest > checked_at:
+            run_command(args, opts.verbose)
+        checked_at = time.time()
+        time.sleep(opts.check)
+
+def loop(opts, args):
+    if opts.update:
+        update_at_intervals(args, opts)
+    elif opts.check:
+        check_at_intervals(args, opts)
+    else:
+        raise NotImplementedError('we must implement!!!')
+
+def main():
+    opts, args = get_args()
+    try:
+        loop(opts, args)
+    except KeyboardInterrupt:
+        pass
+
+if __name__ == '__main__':
+    main()
+