Difference between revisions of "Skel.py"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
Line 1: | Line 1: | ||
=Intro= | |||
My skeleton Python scripts... | My skeleton Python scripts... |
Revision as of 18:05, 2 May 2008
Intro
My skeleton Python scripts...
Version Incorporating Python Logging
#!/usr/bin/env python # # Purpose: Skeleton Python script # # $Id:$ # #------------------------------------------------------------------------------- """ Skeleton Python script ... """ #------------------------------------------------------------------------------- import os import re import sys import getopt import logging #------------------------------------------------------------------------------- from datetime import datetime #------------------------------------------------------------------------------- __version__ = "1.0.0" __id__ = "@(#) skel.py [%s] 2008-05-03" debug_level = 0 verbose_flg = False LOGFILE = "log/skel.log" PIDFILE = "DATA/skel.pid" tables = [] log = None pid = None #=============================================================================== def INFO(msg): if log: log.info(' ' + msg) if verbose_flg: print "[skel] %s" % msg #------------------------------------------------------------------------------- def ERROR(msg): if log: log.error(msg) sys.stderr.write('[skel] %s\n' % msg) #------------------------------------------------------------------------------- def WARNING(msg): if log: log.warning('*****' + msg + '*****') if verbose_flg: print "[skel] %s" % msg #=============================================================================== def init(): global log global pid pid = os.getpid() log = logging.getLogger('skel') hdlr = logging.FileHandler(LOGFILE) fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(fmtr) log.addHandler(hdlr) log.setLevel(logging.INFO) INFO("Started processing with PID %d" % pid) if (not verbose_flg): INFO("PID is %d" % pid) #=============================================================================== def the_time(): t = float(ref_time(False)) * 0.001 return t #------------------------------------------------------------------------------ t_reference = None def ref_time(flg): global t_reference t_now = datetime.now() if (flg): t_reference = t_now t = 0 else: t_delta = t_now - t_reference t = ((t_delta.seconds * 1000000) + t_delta.microseconds)/1000.0 return t #=============================================================================== def main(): global verbose_flg global debug_level try: opts, args = getopt.getopt(sys.argv[1:], "dD:vVw?") except getopt.error, msg: print __doc__ return 1 try: terminal_type = os.environ["TERM"] except KeyError, e: print "Set TERM environment variable and rerun!" return 1 wrk_path = os.getcwd() wrk_dir = os.path.basename(wrk_path) data_dir = wrk_dir + '/DATA/' pid_path = data_dir + PIDFILE # os.chdir(data_dir) for o, a in opts: if o == '-d': debug_level += 1 elif o == '-D': debug_level = int(a) elif o == '-v': verbose_flg = True elif o == '-V': print "[skel] Version: %s" % __version__ return 1 elif o == '-?': print __doc__ return 1 print "[skel] Working directory is %s" % os.getcwd() if (debug_level > 0): print "Debugging level set to %d" % debug_level if args: for arg in args: print arg init() return 0 #------------------------------------------------------------------------------- if __name__ == '__main__' or __name__ == sys.argv[0]: try: sys.exit(main()) except KeyboardInterrupt, e: print "[skel] Interrupted!" #------------------------------------------------------------------------------- """ Revision History: Date Who Description -------- --- ------------------------------------------------------------ 20031014 plh Initial implementation Problems to fix: To Do: Issues: """
Version Incorporating Dates
#!/usr/bin/env python # # Author: Peter Harding <plh@performiq.com.au> # # PerformIQ Pty. Ltd. # Level 6, # 170 Queen Street, # MELBOURNE, VIC, 3000 # # Phone: 03 9641 2222 # Fax: 03 9641 2200 # Mobile: 0418 375 085 # # Copyright (C) PerformIQ Pty Ltd, 1992-2005 # All rights reserved # # @(#) [1.0.01] skel.py 2006-03-07 # # # NAME # skel.py - Sample script # # SYNOPSIS # skel.py [-dv] [-D <DATE>|-S <STARTDATE>|-E <ENDDATE>] # # PARAMETERS # -D <DATE> Date (in ISO format # -d Debug # -v Verbose # # DESCRIPTION # ... # # RETURNS # 0 for successful completion, 1 for any error # # FILES # ... # # $Id:$ # #--------------------------------------------------------------------- """ ... """ #--------------------------------------------------------------------- import sys import getopt #--------------------------------------------------------------------- debug_level = 0 verbose_flg = True #--------------------------------------------------------------------- def is_weekday(dow): if ((dow >= 0) and (dow <=4)): return 1 else: return 0 #--------------------------------------------------------------------- def to_datetime(date): date = int(date) mday = date % 100 month = ( date % 10000) / 100 year = date / 10000 return datetime.date(day=mday, month=month, year=year) #--------------------------------------------------------------------- def main(): global debug_flg global verbose_flg if None: try: userId = os.environ['USER'] except: print "***** USER environment variable not set" # sys.exit(0) try: opts, args = getopt.getopt(sys.argv[1:], "dD:E:S:vVY?") except getopt.error, msg: print __doc__ return 1 date = None start_date = None end_date = None for o, a in opts: if o == '-?': print __doc__ return 1 elif o == '-d': debug_level += 1 elif o == '-D': date = to_datetime(a) elif o == '-E': end_date = to_datetime(a) elif o == '-S': start_date = to_datetime(a) elif o == '-Y': date = datetime.date.today() - datetime.timedelta(days=1) elif o == '-v': verbose_flg = True elif o == '-V': print "Version: %s" % __version__ return 1 else: return 1 return 1 #--------------------------------------------------------------------- if __name__ == '__main__' or __name__ == sys.argv[0]: try: sys.exit(main()) except KeyboardInterrupt, e: print "[skel] Interrupted!" #--------------------------------------------------------------------- """ Revision History: Date Who Description -------- --- -------------------------------------------------- 20030920 plh Initial implementation 20031002 plh Cleaned up args in main(). Added '-h', '-?', '-V' Problems to fix: To Do: Issues: """
Another Version
#!/usr/bin/env python # # Author: Peter Harding <plh@pha.com.au> # Peter Harding & Associates Pty. Ltd. # Level 6, # 170 Queen Street, # MELBOURNE, VIC, 3000 # # Phone: 03 9641 2222 # Fax: 03 9641 2200 # Mobile: 0418 375 085 # # Purpose: Skeleton python script # # # Copyright (C) Peter Harding, 2003 # All rights reserved # # $Id: skel.py,v 1.1.1.1 2003/10/22 11:57:35 zyx Exp $ # #--------------------------------------------------------------------- """ Skeleton Python Framework Usage: skel.py -g <no> -v The '-g <no>' option is used to specify the number of groups. The '-v' turns on verbose mode. """ #--------------------------------------------------------------------- import os import sys import getopt import string import whrandom #--------------------------------------------------------------------- __version__ = "1.0.0" wrk = None no = None #--------------------------------------------------------------------- def process(): pass #--------------------------------------------------------------------- def main(): global debugFlg global no global verboseFlg try: opts, args = getopt.getopt(sys.argv[1:], "dg:vV?") except getopt.error, msg: print __doc__, return 1 for o, a in opts: if o == '-d': debugFlg = 1 elif o == '-g': no = int(a) elif o == '-v': verboseFlg = 1 elif o == '-V': print "Version: %s" % __version__ return 0 elif o == '-?': print __doc__() return 0 if args: for arg in args: process arg global wrk wrk = os.getcwd() process() #--------------------------------------------------------------------- if __name__ == '__main__' or __name__ == sys.argv[0]: sys.exit(main()) #--------------------------------------------------------------------- """ Revision History: Date Who Description -------- --- -------------------------------------------------- 20030920 plh Initial implementation 20031002 plh Cleaned up args in main(). Added '-h', '-?', '-V' Problems to fix: To Do: Issues: """