#! /usr/bin/env python # ====================================================================== # # Filename: scriptutil.py # # Created: 01-DEC-1999, Harry L. Melanson # # ====================================================================== """A set of utilities for writing python scripts. This module contains utilities used to write python scripts. """ # ====================================================================== import sys import os import string import re # ====================================================================== __author__ = 'Harry L. Melanson, melanson@fnal.gov' __version__ = '00.00.01' __filename__ = 'scriptutil.py' __doc__ = __doc__ % vars() # ====================================================================== def errorMsg(msg, doc=""): sys.stderr.write('\nERROR: %s: %s\n' % (os.path.basename(sys.argv[0]), msg)) print "\n" + msg sys.stderr.write(doc) print "\n" + 50*"-" # ====================================================================== def FatalError(msg, doc=""): sys.stderr.write('\nERROR: %s: %s\n' % (os.path.basename(sys.argv[0]), msg)) sys.stderr.write(doc) print "\n" + 50*"-" sys.exit(-1) # ====================================================================== class Option: """A command line option. **Public Data Members:** * flag: The option flag (eg. -h) * value: The option value (if any) **Constructor:** Option(flag, value) """ def __init__(self, flag, value): self.flag = flag self.value = value # ====================================================================== class ConfigOptions: """A collection of configuration options and switches.""" def __init__(self): self.options = {} self.switches = {} def __repr__(self): s = [] s.append('\nOptions\n') for key in self.options.keys(): s.append('%s = %s\n' % (key, self.options[key])) s.append('\nSwitches\n') for key in self.switches.keys(): s.append('%s = %s\n' % (key, self.switches[key])) return string.join(s, '') def opt(self, key): if self.options.has_key(key): return self.options[key] else: print print "ERROR: Option", key, "does not exist." print return None def switch(self, key): if self.switches.has_key(key): return self.switches[key] else: print print "ERROR: Switch", key, "does not exist." print return None # ====================================================================== # ====================================================================== def getOptions(options, long_options, doc): """Get options from the command line. Supports -h, -?, --help options automatically. If user specifies -h, -? or --help on the command line, then the calling module's documentation is displayed, and the command exits. **Arguments:** * options: allowed options (see getopt module) * long_options: allowed long options (see getopt module) * doc: documenation used when -h option selected (eg. calling module's __doc__ string) **Return Values:** * optlist: list of Option's * args: list of command arguments """ import getopt import os # ---------------------------------------- # Support -h, -?, --help allowed_options = options + 'h?' allowed_long_options = long_options allowed_long_options.append('help') # ----------------------------------------------------- # Get options from command line, and process any error try: opts, args = getopt.getopt(sys.argv[1:], allowed_options, allowed_long_options) except getopt.error, msg: sys.stderr.write('\nERROR: %s: %s\n' % (os.path.basename(sys.argv[0]), msg)) sys.stderr.write(doc) sys.exit(-1) # ---------------------------------------- # Support help option for opt in opts: if opt[0] in ('-h', '-?', '--help'): print "\nNAME: ", (os.path.basename(sys.argv[0])) print "\n", doc sys.exit(0) # ---------------------------------------- # Make a list of Option's optlist = [] for opt in opts: optlist.append(Option(opt[0],opt[1])) # -------------------------------------------------- # Return the list of Option's and the command arg's return optlist, args # ====================================================================== class FileInfo: """Holds information about a file. **Public Data Members:** * name: file's name (eg. 'readme.txt') * prefix: file's prefix (eg. 'readme') * extension: file's extension (eg. 'txt') * protection: file's protection flags * owner: file's owner * group: file's group * size: file's size * lastmod: file's date of last modification **Constructor:** FileInfo(lsline) * lsline: a line resulting from an ls -la command """ # ---------------------------------------- def __init__(self, lsline): items = string.split(lsline) if len(items) >= 9: filename = string.split(items[8],"/") self.name = filename[len(filename)-1] # Name of file self.prefix = string.join(string.split(self.name,'.')[:-1]) self.extension = string.split(self.name,'.')[-1] # File extension self.protection = items[0] # File protection self.owner = items[2] # File owner self.group = items[3] # File group self.size = items[4] # File size self.lastmod = (items[5] + " " + # Last modified date items[6] + " " + items[7] ) else: raise RuntimeError # ---------------------------------------- def __repr__(self): repr = (self.name + " " + self.owner + " " + self.group + " " + self.size + " " + self.lastmod + " " + self.protection) return repr # ---------------------------------------- def sameFileInfos(a, b, checkowner=1): """Compare two FileInfo's. Return true if they are the same. """ if (a.name == b.name and a.size == b.size and a.lastmod == b.lastmod and a.protection == b.protection): if checkowner: if (a.owner == b.owner and a.group == b.group): return 1 else: return 0 else: return 1 else: return 0 # ====================================================================== def getFileList(dir,filespec): """ Get the list of files in a specified directory. **Arguments:** * dir: the directory * filespec: specifies which files to consider (wildcards supported) **Return value:** * A list of FileInfo's **Limitations:** Only works on systems which support the Unix command *ls -la*. """ # ---------------------------------------- # Build a list of files list = [] # Issue an ls command, and get the list of files if dir[-1] != "/": dir = dir + "/" if filespec == '*': filespec = '' command = "ls -la " + dir + filespec for line in os.popen(command,'r').readlines(): if len(line) >= 6: if line[0:5] != "total": file = FileInfo(line) if file.name != '.' and file.name != '..': list.append(file) return list # ====================================================================== def getDirectories(dir): """Get subdirectories in a given directory. **Arguments:** * dir: the directory **Return:** * A list of FileInfo's which are really directories """ result = [] filelist = getFileList(dir,'') for file in filelist: if file.protection[0] == 'd': result.append(file) return result # ====================================================================== def getFiles(dir, filespec): """Get files in a given directory. **Arguments:** * dir: the directory * filespec: specifies which files to consider (wildcards supported) **Return:** * A list of FileInfo's which are really files (not directories) """ result = [] filelist = getFileList(dir,filespec) for file in filelist: if file.protection[0] != 'd': result.append(file) return result # ====================================================================== # Self-test if __name__ == '__main__': sys.exit()