'mpptg module initializer and generic utilities' __revision__ = '$Id: //depot/devuser/jsmith/tcdev_1.5.X/lib/mpptg/__init__.py#6 $' __metaclass__ = type import os import sys import re import marshal import cPickle class PlatformError(Exception): 'Used to indicate an unsupported platform' def __init__(self, platform): Exception.__init__(self, platform) self.platform = platform def __str__(self): return 'unsupported: ' + self.platform class CommandError(Exception): 'Base class for command runtime exceptions' class SerializeError(CommandError): 'Used to indicate serialization errors ' def __init__(self, cmd): CommandError.__init__(self, cmd) self.cmd = cmd def __str__(self): return 'bad serialization when running: ' + self.cmd class StderrError(CommandError): 'Used to indicate error output from a command' def __init__(self, cmd, errlines, output): CommandError.__init__(self, cmd, errlines, output) self.cmd = cmd self.errlines = errlines self.output = output def __str__(self): return 'error output when running: ' + self.cmd + '\n' + ''.join(self.errlines) def expandvars(instr, varblock): 'string expandvars(string input, dictionary varlist)' if sys.platform == 'win32': var = re.compile(r'%(\w+)%') instr = var.sub(r'${\1}', instr) keeper = os.environ os.environ = varblock outstr = os.path.expandvars(instr) os.environ = keeper return outstr def syscmd(cmd, inputlines=False, mode='t', running=False, serialize=False, prereaderr=False, serialver=0): 'Run a system command' serializers = {'marshal': marshal, 'pickle': cPickle} # Marshalling requires binary streams and running must be turned off if serialize: mode = 'b' running = False serializer = serializers[serialize] # Get the current value of the Python buffering environment so it can be # restored. Set Python to unbuffered if running output was requested. pythonbuffering = os.environ.get('PYTHONUNBUFFERED') if running: os.environ['PYTHONUNBUFFERED'] = '1' (stdin, stdout, stderr) = os.popen3(cmd, mode) # Restore the Python buffering to the previous value if pythonbuffering: os.environ['PYTHONUNBUFFERED'] = pythonbuffering if inputlines: if serialize: serializer.dump(inputlines, stdin, serialver) else: stdin.writelines(inputlines) stdin.close() errlines = list() if prereaderr: errlines = stderr.readlines() outlines = list() if running: while 1: line = stdout.readline() if not line: break sys.stdout.write(line) outlines.append(line) elif serialize: while 1: try: item = serializer.load(stdout) outlines.append(item) except EOFError: break except ValueError: stdout.close() stderr.close() raise SerializeError(cmd) else: outlines = stdout.readlines() stdout.close() errlines += stderr.readlines() stderr.close() if errlines: raise StderrError(cmd, errlines, outlines) return outlines