import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) class Script(object): def openPipe(command): '''We need to use the asynchronous version here since we want to avoid blocking reads''' import popen2 pipe = None if hasattr(popen2, 'Popen3'): pipe = popen2.Popen3(command, 1) input = pipe.tochild output = pipe.fromchild err = pipe.childerr else: import os (input, output, err) = os.popen3(command) return (input, output, err, pipe) openPipe = staticmethod(openPipe) def runShellCommand(command, log = None): import select ret = None out = '' err = '' loginError = 0 if log: log.write('Executing: '+command+'\n') (input, output, error, pipe) = Script.openPipe(command) input.close() outputClosed = 0 errorClosed = 0 lst = [output, error] while 1: ready = select.select(lst, [], []) if len(ready[0]): if error in ready[0]: msg = error.readline() if msg: err += msg else: errorClosed = 1 lst.remove(error) if output in ready[0]: msg = output.readline() if msg: out += msg else: outputClosed = 1 lst.remove(output) if out.find('password:') >= 0 or err.find('password:') >= 0: loginError = 1 break if outputClosed and errorClosed: break output.close() error.close() if pipe: # We would like the NOHANG argument here ret = pipe.wait() if loginError: raise RuntimeError('Could not login to site') return (out, err, ret) runShellCommand = staticmethod(runShellCommand) if __name__ == "__main__": import sys (out, err, ret) = Script.runShellCommand(" ".join(sys.argv[1:]), log=sys.stdout) print "out: %s" % out print "err: %s" % out print "ret: %d" % ret