import os, traceback, sys class ExternalCommandErrorWithOutputList(Exception): def __init__(self,args=None): if args: self.args = args[0] self.outputList = args[1] else: self.args = args self.outputList = [] def executeCommandReturnOutput(args): args_str = ' '.join(args) if os.name not in ['nt', 'os2']: import popen2 p = popen2.Popen4(args_str) p.tochild.close() outputList = p.fromchild.readlines() exitCode = p.wait() if exitCode == 0: exitCode = None else: exitCode >>= 8 else: i,k = os.popen4(args_str) i.close() outputList = k.readlines() exitCode = k.close() if exitCode is not None: raise ExternalCommandErrorWithOutputList, [exitCode, outputList] return outputList if __name__ == "__main__": for cmd in [['python', '-c', r'print 5'], ['python', '-c', r'1/0'], ['python', '-c', r'print 6;import sys;sys.stdout.flush();print >>sys.stderr, 7;print 8']]: try: ret = executeCommandReturnOutput(cmd) print 'ret', ret except executeCommandReturnOutput, e: print 'executeCommandReturnOutput', e, e.outputList except Exception, e: print 'Exception', e type, value, stack = sys.exc_info() print ''.join(traceback.format_exception(type, value, stack)) except: print 'except' type, value, stack = sys.exc_info() print ''.join(traceback.format_exception(type, value, stack)) else: print 'else' print '*' * 20