michael@0: #!/usr/bin/env python michael@0: # Copyright (c) 2002-2003 ActiveState Corp. michael@0: # Author: Trent Mick (TrentM@ActiveState.com) michael@0: michael@0: import os michael@0: import sys michael@0: import types michael@0: michael@0: michael@0: #---- Support routines michael@0: michael@0: def _escapeArg(arg): michael@0: """Escape the given command line argument for the shell.""" michael@0: #XXX There is a *lot* more that we should escape here. michael@0: return arg.replace('"', r'\"') michael@0: michael@0: michael@0: def _joinArgv(argv): michael@0: r"""Join an arglist to a string appropriate for running. michael@0: >>> import os michael@0: >>> _joinArgv(['foo', 'bar "baz']) michael@0: 'foo "bar \\"baz"' michael@0: """ michael@0: cmdstr = "" michael@0: for arg in argv: michael@0: if ' ' in arg: michael@0: cmdstr += '"%s"' % _escapeArg(arg) michael@0: else: michael@0: cmdstr += _escapeArg(arg) michael@0: cmdstr += ' ' michael@0: if cmdstr.endswith(' '): cmdstr = cmdstr[:-1] # strip trailing space michael@0: return cmdstr michael@0: michael@0: michael@0: def run(argv): michael@0: """Prepare and run the given arg vector, 'argv', and return the michael@0: results. Returns (, , ). michael@0: Note: 'argv' may also just be the command string. michael@0: """ michael@0: if type(argv) in (types.ListType, types.TupleType): michael@0: cmd = _joinArgv(argv) michael@0: else: michael@0: cmd = argv michael@0: if sys.platform.startswith('win'): michael@0: i, o, e = os.popen3(cmd) michael@0: output = o.read() michael@0: error = e.read() michael@0: i.close() michael@0: e.close() michael@0: try: michael@0: retval = o.close() michael@0: except IOError: michael@0: # IOError is raised iff the spawned app returns -1. Go michael@0: # figure. michael@0: retval = -1 michael@0: if retval is None: michael@0: retval = 0 michael@0: else: michael@0: import popen2 michael@0: p = popen2.Popen3(cmd, 1) michael@0: i, o, e = p.tochild, p.fromchild, p.childerr michael@0: output = o.read() michael@0: error = e.read() michael@0: i.close() michael@0: o.close() michael@0: e.close() michael@0: retval = (p.wait() & 0xFF00) >> 8 michael@0: if retval > 2**7: # 8-bit signed 1's-complement conversion michael@0: retval -= 2**8 michael@0: return output, error, retval michael@0: michael@0: michael@0: def _rmtreeOnError(rmFunction, filePath, excInfo): michael@0: if excInfo[0] == OSError: michael@0: # presuming because file is read-only michael@0: os.chmod(filePath, 0777) michael@0: rmFunction(filePath) michael@0: michael@0: def rmtree(dirname): michael@0: import shutil michael@0: shutil.rmtree(dirname, 0, _rmtreeOnError) michael@0: michael@0: