1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/python/which/test/testsupport.py Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,83 @@ 1.4 +#!/usr/bin/env python 1.5 +# Copyright (c) 2002-2003 ActiveState Corp. 1.6 +# Author: Trent Mick (TrentM@ActiveState.com) 1.7 + 1.8 +import os 1.9 +import sys 1.10 +import types 1.11 + 1.12 + 1.13 +#---- Support routines 1.14 + 1.15 +def _escapeArg(arg): 1.16 + """Escape the given command line argument for the shell.""" 1.17 + #XXX There is a *lot* more that we should escape here. 1.18 + return arg.replace('"', r'\"') 1.19 + 1.20 + 1.21 +def _joinArgv(argv): 1.22 + r"""Join an arglist to a string appropriate for running. 1.23 + >>> import os 1.24 + >>> _joinArgv(['foo', 'bar "baz']) 1.25 + 'foo "bar \\"baz"' 1.26 + """ 1.27 + cmdstr = "" 1.28 + for arg in argv: 1.29 + if ' ' in arg: 1.30 + cmdstr += '"%s"' % _escapeArg(arg) 1.31 + else: 1.32 + cmdstr += _escapeArg(arg) 1.33 + cmdstr += ' ' 1.34 + if cmdstr.endswith(' '): cmdstr = cmdstr[:-1] # strip trailing space 1.35 + return cmdstr 1.36 + 1.37 + 1.38 +def run(argv): 1.39 + """Prepare and run the given arg vector, 'argv', and return the 1.40 + results. Returns (<stdout lines>, <stderr lines>, <return value>). 1.41 + Note: 'argv' may also just be the command string. 1.42 + """ 1.43 + if type(argv) in (types.ListType, types.TupleType): 1.44 + cmd = _joinArgv(argv) 1.45 + else: 1.46 + cmd = argv 1.47 + if sys.platform.startswith('win'): 1.48 + i, o, e = os.popen3(cmd) 1.49 + output = o.read() 1.50 + error = e.read() 1.51 + i.close() 1.52 + e.close() 1.53 + try: 1.54 + retval = o.close() 1.55 + except IOError: 1.56 + # IOError is raised iff the spawned app returns -1. Go 1.57 + # figure. 1.58 + retval = -1 1.59 + if retval is None: 1.60 + retval = 0 1.61 + else: 1.62 + import popen2 1.63 + p = popen2.Popen3(cmd, 1) 1.64 + i, o, e = p.tochild, p.fromchild, p.childerr 1.65 + output = o.read() 1.66 + error = e.read() 1.67 + i.close() 1.68 + o.close() 1.69 + e.close() 1.70 + retval = (p.wait() & 0xFF00) >> 8 1.71 + if retval > 2**7: # 8-bit signed 1's-complement conversion 1.72 + retval -= 2**8 1.73 + return output, error, retval 1.74 + 1.75 + 1.76 +def _rmtreeOnError(rmFunction, filePath, excInfo): 1.77 + if excInfo[0] == OSError: 1.78 + # presuming because file is read-only 1.79 + os.chmod(filePath, 0777) 1.80 + rmFunction(filePath) 1.81 + 1.82 +def rmtree(dirname): 1.83 + import shutil 1.84 + shutil.rmtree(dirname, 0, _rmtreeOnError) 1.85 + 1.86 +