home *** CD-ROM | disk | FTP | other *** search
Wrap
# Source Generated with Decompyle++ # File: in.pyc (Python 2.6) import optparse import os import sys import pexpect USAGE = '\nInteractive script runner, type: %s\n\nrunner [opts] script_name\n' def pexpect_monkeypatch(): if pexpect.__version__[:3] >= '2.2': return None def __del__(self): if not self.closed: try: self.close() except AttributeError: pass except: None<EXCEPTION MATCH>AttributeError None<EXCEPTION MATCH>AttributeError pexpect.spawn.__del__ = __del__ pexpect_monkeypatch() class InteractiveRunner(object): def __init__(self, program, prompts, args = None, out = sys.stdout, echo = True): self.program = program self.prompts = prompts if args is None: args = [] self.args = args self.out = out self.echo = echo self.delaybeforesend = 0 c = self.child = pexpect.spawn(self.program, self.args, timeout = None) c.delaybeforesend = self.delaybeforesend c.setwinsize(99, 200) def close(self): self.child.close() def run_file(self, fname, interact = False, get_output = False): fobj = open(fname, 'r') try: out = self.run_source(fobj, interact, get_output) finally: fobj.close() if get_output: return out def run_source(self, source, interact = False, get_output = False): if not isinstance(source, file): source = source.splitlines(True) if self.echo: linesep = os.linesep stdwrite = self.out.write write = lambda s: stdwrite(s.replace('\r\n', linesep)) else: write = lambda s: pass c = self.child prompts = c.compile_pattern_list(self.prompts) prompt_idx = c.expect_list(prompts) end_normal = True if get_output: output = [] store_output = output.append for cmd in source: if prompt_idx == 0: if cmd.isspace() or cmd.lstrip().startswith('#'): write(cmd) continue write(c.after) c.send(cmd) try: prompt_idx = c.expect_list(prompts) except pexpect.EOF: write(c.before) end_normal = False break write(c.before) if get_output: store_output(c.before[len(cmd + '\n'):]) continue self.out.flush() if end_normal: if interact: c.send('\n') print '<< Starting interactive mode >>', try: c.interact() except OSError: write(' \n') self.out.flush() except: None<EXCEPTION MATCH>OSError None<EXCEPTION MATCH>OSError elif interact: e = 'Further interaction is not possible: child process is dead.' print >>sys.stderr, e c.send('\n') if get_output: return ''.join(output) def main(self, argv = None): parser = optparse.OptionParser(usage = USAGE % self.__class__.__name__) newopt = parser.add_option newopt('-i', '--interact', action = 'store_true', default = False, help = 'Interact with the program after the script is run.') (opts, args) = parser.parse_args(argv) if len(args) != 1: print >>sys.stderr, 'You must supply exactly one file to run.' sys.exit(1) self.run_file(args[0], opts.interact) class IPythonRunner(InteractiveRunner): def __init__(self, program = 'ipython', args = None, out = sys.stdout, echo = True): args0 = [ '-colors', 'NoColor', '-pi1', 'In [\\#]: ', '-pi2', ' .\\D.: ', '-noterm_title', '-noautoindent'] if args is None: args = args0 else: args = args0 + args prompts = [ 'In \\[\\d+\\]: ', ' \\.*: '] InteractiveRunner.__init__(self, program, prompts, args, out, echo) class PythonRunner(InteractiveRunner): def __init__(self, program = 'python', args = None, out = sys.stdout, echo = True): prompts = [ '>>> ', '\\.\\.\\. '] InteractiveRunner.__init__(self, program, prompts, args, out, echo) class SAGERunner(InteractiveRunner): def __init__(self, program = 'sage', args = None, out = sys.stdout, echo = True): prompts = [ 'sage: ', '\\s*\\.\\.\\. '] InteractiveRunner.__init__(self, program, prompts, args, out, echo) class RunnerFactory(object): def __init__(self, out = sys.stdout): self.out = out self.runner = None self.runnerClass = None def _makeRunner(self, runnerClass): self.runnerClass = runnerClass self.runner = runnerClass(out = self.out) return self.runner def __call__(self, fname): if fname.endswith('.py'): runnerClass = PythonRunner elif fname.endswith('.ipy'): runnerClass = IPythonRunner else: raise ValueError('Unknown file type for Runner: %r' % fname) if fname.endswith('.py').runner is None: return self._makeRunner(runnerClass) if runnerClass == self.runnerClass: return self.runner e = 'A runner of type %r can not run file %r' % (self.runnerClass, fname) raise ValueError(e) MAIN_USAGE = "\n%prog [options] file_to_run\n\nThis is an interface to the various interactive runners available in this\nmodule. If you want to pass specific options to one of the runners, you need\nto first terminate the main options with a '--', and then provide the runner's\noptions. For example:\n\nirunner.py --python -- --help\n\nwill pass --help to the python runner. Similarly,\n\nirunner.py --ipython -- --interact script.ipy\n\nwill run the script.ipy file under the IPython runner, and then will start to\ninteract with IPython at the end of the script (instead of exiting).\n\nThe already implemented runners are listed below; adding one for a new program\nis a trivial task, see the source for examples.\n\nWARNING: the SAGE runner only works if you manually configure your SAGE copy\nto use 'colors NoColor' in the ipythonrc config file, since currently the\nprompt matching regexp does not identify color sequences.\n" def main(): parser = optparse.OptionParser(usage = MAIN_USAGE) newopt = parser.add_option parser.set_defaults(mode = 'ipython') newopt('--ipython', action = 'store_const', dest = 'mode', const = 'ipython', help = 'IPython interactive runner (default).') newopt('--python', action = 'store_const', dest = 'mode', const = 'python', help = 'Python interactive runner.') newopt('--sage', action = 'store_const', dest = 'mode', const = 'sage', help = 'SAGE interactive runner.') (opts, args) = parser.parse_args() runners = dict(ipython = IPythonRunner, python = PythonRunner, sage = SAGERunner) try: ext = os.path.splitext(args[0])[-1] except IndexError: ext = '' modes = { '.ipy': 'ipython', '.py': 'python', '.sage': 'sage' } mode = modes.get(ext, opts.mode) runners[mode]().main(args) if __name__ == '__main__': main()