home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1831 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  8.5 KB  |  242 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import optparse
  5. import os
  6. import sys
  7. import pexpect
  8. USAGE = '\nInteractive script runner, type: %s\n\nrunner [opts] script_name\n'
  9.  
  10. def pexpect_monkeypatch():
  11.     if pexpect.__version__[:3] >= '2.2':
  12.         return None
  13.     
  14.     def __del__(self):
  15.         if not self.closed:
  16.             
  17.             try:
  18.                 self.close()
  19.             except AttributeError:
  20.                 pass
  21.             except:
  22.                 None<EXCEPTION MATCH>AttributeError
  23.             
  24.  
  25.         None<EXCEPTION MATCH>AttributeError
  26.  
  27.     pexpect.spawn.__del__ = __del__
  28.  
  29. pexpect_monkeypatch()
  30.  
  31. class InteractiveRunner(object):
  32.     
  33.     def __init__(self, program, prompts, args = None, out = sys.stdout, echo = True):
  34.         self.program = program
  35.         self.prompts = prompts
  36.         if args is None:
  37.             args = []
  38.         
  39.         self.args = args
  40.         self.out = out
  41.         self.echo = echo
  42.         self.delaybeforesend = 0
  43.         c = self.child = pexpect.spawn(self.program, self.args, timeout = None)
  44.         c.delaybeforesend = self.delaybeforesend
  45.         c.setwinsize(99, 200)
  46.  
  47.     
  48.     def close(self):
  49.         self.child.close()
  50.  
  51.     
  52.     def run_file(self, fname, interact = False, get_output = False):
  53.         fobj = open(fname, 'r')
  54.         
  55.         try:
  56.             out = self.run_source(fobj, interact, get_output)
  57.         finally:
  58.             fobj.close()
  59.  
  60.         if get_output:
  61.             return out
  62.  
  63.     
  64.     def run_source(self, source, interact = False, get_output = False):
  65.         if not isinstance(source, file):
  66.             source = source.splitlines(True)
  67.         
  68.         if self.echo:
  69.             linesep = os.linesep
  70.             stdwrite = self.out.write
  71.             
  72.             write = lambda s: stdwrite(s.replace('\r\n', linesep))
  73.         else:
  74.             
  75.             write = lambda s: pass
  76.         c = self.child
  77.         prompts = c.compile_pattern_list(self.prompts)
  78.         prompt_idx = c.expect_list(prompts)
  79.         end_normal = True
  80.         if get_output:
  81.             output = []
  82.             store_output = output.append
  83.         
  84.         for cmd in source:
  85.             if prompt_idx == 0:
  86.                 if cmd.isspace() or cmd.lstrip().startswith('#'):
  87.                     write(cmd)
  88.                     continue
  89.                 
  90.             write(c.after)
  91.             c.send(cmd)
  92.             
  93.             try:
  94.                 prompt_idx = c.expect_list(prompts)
  95.             except pexpect.EOF:
  96.                 write(c.before)
  97.                 end_normal = False
  98.                 break
  99.  
  100.             write(c.before)
  101.             if get_output:
  102.                 store_output(c.before[len(cmd + '\n'):])
  103.                 continue
  104.         
  105.         self.out.flush()
  106.         if end_normal:
  107.             if interact:
  108.                 c.send('\n')
  109.                 print '<< Starting interactive mode >>',
  110.                 
  111.                 try:
  112.                     c.interact()
  113.                 except OSError:
  114.                     write(' \n')
  115.                     self.out.flush()
  116.                 except:
  117.                     None<EXCEPTION MATCH>OSError
  118.                 
  119.  
  120.             None<EXCEPTION MATCH>OSError
  121.         elif interact:
  122.             e = 'Further interaction is not possible: child process is dead.'
  123.             print >>sys.stderr, e
  124.         
  125.         c.send('\n')
  126.         if get_output:
  127.             return ''.join(output)
  128.  
  129.     
  130.     def main(self, argv = None):
  131.         parser = optparse.OptionParser(usage = USAGE % self.__class__.__name__)
  132.         newopt = parser.add_option
  133.         newopt('-i', '--interact', action = 'store_true', default = False, help = 'Interact with the program after the script is run.')
  134.         (opts, args) = parser.parse_args(argv)
  135.         if len(args) != 1:
  136.             print >>sys.stderr, 'You must supply exactly one file to run.'
  137.             sys.exit(1)
  138.         
  139.         self.run_file(args[0], opts.interact)
  140.  
  141.  
  142.  
  143. class IPythonRunner(InteractiveRunner):
  144.     
  145.     def __init__(self, program = 'ipython', args = None, out = sys.stdout, echo = True):
  146.         args0 = [
  147.             '-colors',
  148.             'NoColor',
  149.             '-pi1',
  150.             'In [\\#]: ',
  151.             '-pi2',
  152.             '   .\\D.: ',
  153.             '-noterm_title',
  154.             '-noautoindent']
  155.         if args is None:
  156.             args = args0
  157.         else:
  158.             args = args0 + args
  159.         prompts = [
  160.             'In \\[\\d+\\]: ',
  161.             '   \\.*: ']
  162.         InteractiveRunner.__init__(self, program, prompts, args, out, echo)
  163.  
  164.  
  165.  
  166. class PythonRunner(InteractiveRunner):
  167.     
  168.     def __init__(self, program = 'python', args = None, out = sys.stdout, echo = True):
  169.         prompts = [
  170.             '>>> ',
  171.             '\\.\\.\\. ']
  172.         InteractiveRunner.__init__(self, program, prompts, args, out, echo)
  173.  
  174.  
  175.  
  176. class SAGERunner(InteractiveRunner):
  177.     
  178.     def __init__(self, program = 'sage', args = None, out = sys.stdout, echo = True):
  179.         prompts = [
  180.             'sage: ',
  181.             '\\s*\\.\\.\\. ']
  182.         InteractiveRunner.__init__(self, program, prompts, args, out, echo)
  183.  
  184.  
  185.  
  186. class RunnerFactory(object):
  187.     
  188.     def __init__(self, out = sys.stdout):
  189.         self.out = out
  190.         self.runner = None
  191.         self.runnerClass = None
  192.  
  193.     
  194.     def _makeRunner(self, runnerClass):
  195.         self.runnerClass = runnerClass
  196.         self.runner = runnerClass(out = self.out)
  197.         return self.runner
  198.  
  199.     
  200.     def __call__(self, fname):
  201.         if fname.endswith('.py'):
  202.             runnerClass = PythonRunner
  203.         elif fname.endswith('.ipy'):
  204.             runnerClass = IPythonRunner
  205.         else:
  206.             raise ValueError('Unknown file type for Runner: %r' % fname)
  207.         if fname.endswith('.py').runner is None:
  208.             return self._makeRunner(runnerClass)
  209.         if runnerClass == self.runnerClass:
  210.             return self.runner
  211.         e = 'A runner of type %r can not run file %r' % (self.runnerClass, fname)
  212.         raise ValueError(e)
  213.  
  214.  
  215. 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"
  216.  
  217. def main():
  218.     parser = optparse.OptionParser(usage = MAIN_USAGE)
  219.     newopt = parser.add_option
  220.     parser.set_defaults(mode = 'ipython')
  221.     newopt('--ipython', action = 'store_const', dest = 'mode', const = 'ipython', help = 'IPython interactive runner (default).')
  222.     newopt('--python', action = 'store_const', dest = 'mode', const = 'python', help = 'Python interactive runner.')
  223.     newopt('--sage', action = 'store_const', dest = 'mode', const = 'sage', help = 'SAGE interactive runner.')
  224.     (opts, args) = parser.parse_args()
  225.     runners = dict(ipython = IPythonRunner, python = PythonRunner, sage = SAGERunner)
  226.     
  227.     try:
  228.         ext = os.path.splitext(args[0])[-1]
  229.     except IndexError:
  230.         ext = ''
  231.  
  232.     modes = {
  233.         '.ipy': 'ipython',
  234.         '.py': 'python',
  235.         '.sage': 'sage' }
  236.     mode = modes.get(ext, opts.mode)
  237.     runners[mode]().main(args)
  238.  
  239. if __name__ == '__main__':
  240.     main()
  241.  
  242.