Advertisement
Guest User

itc_d.py

a guest
Dec 19th, 2011
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. #REFERENCES#
  4. __author__ = "Corey M. Farmer - 2011"
  5. __version__ = "1.1"
  6.  
  7. '''DESCRIPTION: this program is designed to:
  8. 1) run as a system process daemon (background process)
  9. 2) read given directory for file feeds from ITC (managed by Robie Bennett)
  10. 3) parse and write the file contents to a mysql datatable
  11. 4) delete file after job completion
  12.  
  13. Exception Handling:
  14. program errors will be handled via commonfunctionlibrary.buildEmailGen() method
  15. and sent to the system adminMailingList defined in given module.
  16.  
  17. errors encountered from ITC files will prompt a file rename to 'invError_' + [filename]
  18. and excluded from future directory iterator instances.'''
  19. #END REFERENCES#
  20.  
  21. import sys, os
  22. sys.path.append( '/home/coreyf/applications/common' )
  23. import commonfunctionlibrary as comfunclib
  24.  
  25. def checkIfRunning():
  26.     '''This method verifies that an instance of this program is not already running.  
  27.     If count of process id`s is greater than 1 close program.'''
  28.  
  29.     if len( os.popen( "ps -aef | grep -i 'itc_d.py' | grep -v 'grep' | awk '{ print $3 }'" ).read().strip().split( '\n' ) ) > 1:
  30.         raise SystemExit(0)
  31.  
  32. def createDaemon():
  33.     '''This method sends the itc_d.py program to the command shell background process list;
  34.     freeing up the shell CLI for user input again while the program continues to execute.'''
  35.  
  36.     try:
  37.         pid = os.fork()
  38.     except OSError, e:
  39.         raise Exception, "%s [%d]" % (e.strerror, e.errno)
  40.     if ( pid == 0 ):
  41.         os.setsid()
  42.         try:
  43.             pid = os.fork()
  44.         except OSError, e:
  45.             raise Exception, "%s [%d]" % (e.strerror, e.errno)
  46.         if ( pid != 0 ): os._exit(0)
  47.     else:
  48.         os._exit(0)
  49.    
  50. def dirIterate():
  51.     '''iterate over "path" variable location searching for files not including
  52.     files with "invError_" in filename.'''
  53.  
  54.     for file in os.listdir( path ):
  55.         if 'invError_' in file: continue
  56.         parseContents( file )
  57.        
  58. def parseContents( file ):
  59.     '''method to parse the contents of individual files, write the data to a mysql table,
  60.     and delete the file after successfully completing previous operations.'''
  61.  
  62.     global aErrorHandler
  63.     errLevel = 0
  64.  
  65.     try:
  66.         fopen = open( path + file )
  67.         try:
  68.             contents = fopen.read().split('|') 
  69.             if len( contents ) == 8:
  70.                 for data in contents:
  71.                        print data
  72.             else:
  73.                 errLevel = 2.1
  74.                 aErrorHandler.append( {'error': 'empty or missing fields in exploded file content!-> expected 8 fields but found ' + str( len( contents ) ), 'file': file, 'caller': 'parseContents::if errLevel:' + str( errLevel ) } )
  75.         finally:
  76.             fopen.close()
  77.     except IOError, e:
  78.         errLevel = 1.1
  79.             aErrorHandler.append( {'error': e.strerror, 'file': file, 'caller': 'parseContents::try errLevel:' + str( errLevel ) } )
  80.  
  81.     pfile = path + file
  82.     if os.path.exists( pfile ):
  83.         os.rename( pfile, path + 'invError_' + file )
  84.    
  85.  
  86.     if errLevel > 0:
  87.         try:
  88.             pass
  89.         except OSError, e:
  90.             errLevel = 1.2
  91.             aErrorHandler.append( {'error': e.strerror, 'file': file, 'caller': 'parseContents::try errLevel:' + str( errLevel ) } )
  92.         finally: pass
  93.        
  94.  
  95. def sendErrorReport():
  96.     '''method designed to handle errors/exceptions encountered within this program
  97.     in a graceful way by notifying the adminMailingList and not raising the system level exception
  98.     (keeping the program from exiting with errors).'''
  99.  
  100.     aAttach = []
  101.     body = '<strong>Error(s) have occurred within the file (' + __file__ + ' )!</strong><br><br>'
  102.     for index, error in enumerate( aErrorHandler ):
  103.         if len( error['file'] ) > 0: aAttach.append( path + error['file'] )
  104.         body += ( str( index+1 ) + ') <strong>Function Name:</strong> ' + error['caller'] +
  105.                      '<br><strong>File Causing Error:</strong> ' + path + error['file'] +
  106.                      '<br><strong>Error:</strong> ' + error['error'] + '<br><br>' )
  107.  
  108.     if len( body ) > 0:
  109.         comfunclib.buildEmailGen( 'USLONSWEB003::pyERROR>>' + __file__, 'adminMailingList', body, aAttach )
  110.  
  111. #begin execution code
  112. path = '/home/coreyf/uslonsweb003/www/systems/txt_test/'
  113.  
  114. def main():
  115.     aErrorHandler = []
  116.  
  117.     #SETUP ENVIRONMENT#
  118.     checkIfRunning() #ensure program is not running as another process already
  119.     #createDaemon() #set program as shell background process (daemonize)
  120.     ###################
  121.  
  122.     dirIterate()
  123.        
  124.     if len( aErrorHandler ) > 0:
  125.         sendErrorReport()
  126.  
  127.     raise SystemExit(0)
  128. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement