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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __docformat__ = 'restructuredtext en'
  5. from types import FunctionType
  6. import __builtin__
  7. import codeop
  8. import compiler
  9. import sys
  10. import traceback
  11. from IPython import ultraTB
  12. from IPython.kernel.core.display_trap import DisplayTrap
  13. from IPython.kernel.core.macro import Macro
  14. from IPython.kernel.core.prompts import CachedOutput
  15. from IPython.kernel.core.traceback_trap import TracebackTrap
  16. from IPython.kernel.core.util import Bunch, system_shell
  17. from IPython.external.Itpl import ItplNS
  18. COMPILER_ERROR = 'error'
  19. INCOMPLETE_INPUT = 'incomplete'
  20. COMPLETE_INPUT = 'complete'
  21. rc = Bunch()
  22. rc.cache_size = 100
  23. rc.pprint = True
  24. rc.separate_in = '\n'
  25. rc.separate_out = '\n'
  26. rc.separate_out2 = ''
  27. rc.prompt_in1 = 'In [\\#]: '
  28. rc.prompt_in2 = '   .\\\\D.: '
  29. rc.prompt_out = ''
  30. rc.prompts_pad_left = False
  31.  
  32. def default_display_formatters():
  33.     PPrintDisplayFormatter = PPrintDisplayFormatter
  34.     ReprDisplayFormatter = ReprDisplayFormatter
  35.     import display_formatter
  36.     return [
  37.         PPrintDisplayFormatter(),
  38.         ReprDisplayFormatter()]
  39.  
  40.  
  41. def default_traceback_formatters():
  42.     PlainTracebackFormatter = PlainTracebackFormatter
  43.     import traceback_formatter
  44.     return [
  45.         PlainTracebackFormatter()]
  46.  
  47.  
  48. class NotDefined(object):
  49.     pass
  50.  
  51.  
  52. class Interpreter(object):
  53.     
  54.     def __init__(self, user_ns = None, global_ns = None, translator = None, magic = None, display_formatters = None, traceback_formatters = None, output_trap = None, history = None, message_cache = None, filename = '<string>', config = None):
  55.         local_ns = user_ns
  56.         if local_ns is None:
  57.             local_ns = { }
  58.         
  59.         self.user_ns = local_ns
  60.         if global_ns is None:
  61.             global_ns = { }
  62.         
  63.         self.user_global_ns = global_ns
  64.         self.translator = translator
  65.         if magic is None:
  66.             Magic = Magic
  67.             import IPython.kernel.core.magic
  68.             magic = Magic(self)
  69.         
  70.         self.magic = magic
  71.         if display_formatters is None:
  72.             display_formatters = default_display_formatters()
  73.         
  74.         self.display_formatters = display_formatters
  75.         if traceback_formatters is None:
  76.             traceback_formatters = default_traceback_formatters()
  77.         
  78.         self.traceback_formatters = traceback_formatters
  79.         if output_trap is None:
  80.             OutputTrap = OutputTrap
  81.             import IPython.kernel.core.output_trap
  82.             output_trap = OutputTrap()
  83.         
  84.         self.output_trap = output_trap
  85.         if history is None:
  86.             InterpreterHistory = InterpreterHistory
  87.             import IPython.kernel.core.history
  88.             history = InterpreterHistory()
  89.         
  90.         self.history = history
  91.         self.get_history_item = history.get_history_item
  92.         self.get_history_input_cache = history.get_input_cache
  93.         self.get_history_input_after = history.get_input_after
  94.         if message_cache is None:
  95.             SimpleMessageCache = SimpleMessageCache
  96.             import IPython.kernel.core.message_cache
  97.             message_cache = SimpleMessageCache()
  98.         
  99.         self.message_cache = message_cache
  100.         self.filename = filename
  101.         if config is None:
  102.             config = Bunch(ESC_MAGIC = '%')
  103.         
  104.         self.config = config
  105.         self.display_trap = DisplayTrap(formatters = self.display_formatters, callbacks = [
  106.             self._possible_macro])
  107.         self.traceback_trap = TracebackTrap(formatters = self.traceback_formatters)
  108.         self.tbHandler = ultraTB.FormattedTB(color_scheme = 'NoColor', mode = 'Context', tb_offset = 2)
  109.         self.command_compiler = codeop.CommandCompiler()
  110.         self.raw_input_builtin = raw_input
  111.         self.input_builtin = input
  112.         self.current_cell_number = 1
  113.         self.outputcache = CachedOutput(self, rc.cache_size, rc.pprint, input_sep = rc.separate_in, output_sep = rc.separate_out, output_sep2 = rc.separate_out2, ps1 = rc.prompt_in1, ps2 = rc.prompt_in2, ps_out = rc.prompt_out, pad_left = rc.prompts_pad_left)
  114.         sys.ps1 = self.outputcache.prompt1.p_str
  115.         sys.ps2 = self.outputcache.prompt2.p_str
  116.         self.message = None
  117.         self.setup_namespace()
  118.  
  119.     
  120.     def formatTraceback(self, et, ev, tb, message = ''):
  121.         tbinfo = self.tbHandler.text(et, ev, tb)
  122.         ev._ipython_traceback_text = tbinfo
  123.         return (et, ev, tb)
  124.  
  125.     
  126.     def execute(self, commands, raiseException = True):
  127.         message = self.setup_message()
  128.         user_input = dict(raw = commands)
  129.         if self.translator is not None:
  130.             python = self.translator(commands, message)
  131.             if python is None:
  132.                 return message
  133.         else:
  134.             python = commands
  135.         user_input['translated'] = python
  136.         message['input'] = user_input
  137.         self.message = message
  138.         self.set_traps()
  139.         status = self.execute_python(python)
  140.         self.unset_traps()
  141.         self.message = None
  142.         if self.history is not None:
  143.             self.history.update_history(self, python)
  144.         
  145.         self.output_trap.add_to_message(message)
  146.         self.output_trap.clear()
  147.         self.display_trap.add_to_message(message)
  148.         self.display_trap.clear()
  149.         self.traceback_trap.add_to_message(message)
  150.         einfo = self.traceback_trap.args
  151.         self.traceback_trap.clear()
  152.         self.message_cache.add_message(self.current_cell_number, message)
  153.         self.current_cell_number += 1
  154.         if raiseException and einfo:
  155.             raise einfo[0], einfo[1], einfo[2]
  156.         einfo
  157.         return message
  158.  
  159.     
  160.     def generate_prompt(self, is_continuation):
  161.         if is_continuation:
  162.             return str(self.outputcache.prompt2)
  163.         return str(self.outputcache.prompt1)
  164.  
  165.     
  166.     def execute_python(self, python):
  167.         
  168.         try:
  169.             commands = self.split_commands(python)
  170.         except (SyntaxError, IndentationError):
  171.             e = None
  172.             self.traceback_trap.args = sys.exc_info()
  173.             self.pack_exception(self.message, e)
  174.             return None
  175.  
  176.         for cmd in commands:
  177.             
  178.             try:
  179.                 code = self.command_compiler(cmd, self.filename, 'single')
  180.             except (SyntaxError, OverflowError, ValueError):
  181.                 e = None
  182.                 self.traceback_trap.args = sys.exc_info()
  183.                 self.pack_exception(self.message, e)
  184.                 return None
  185.  
  186.             self.execute_block(code)
  187.         
  188.  
  189.     
  190.     def execute_block(self, code):
  191.         outflag = 1
  192.         
  193.         try:
  194.             exec code in self.user_ns
  195.             outflag = 0
  196.         except SystemExit:
  197.             self.resetbuffer()
  198.             self.traceback_trap.args = sys.exc_info()
  199.         except:
  200.             self.traceback_trap.args = sys.exc_info()
  201.  
  202.         return outflag
  203.  
  204.     
  205.     def execute_macro(self, macro):
  206.         python = macro.value
  207.         if self.translator is not None:
  208.             python = self.translator(python)
  209.         
  210.         self.execute_python(python)
  211.  
  212.     
  213.     def getCommand(self, i = None):
  214.         return self.message_cache.get_message(i)
  215.  
  216.     
  217.     def reset(self):
  218.         self.user_ns.clear()
  219.         self.setup_namespace()
  220.  
  221.     
  222.     def complete(self, line, text = None, pos = None):
  223.         raise NotImplementedError
  224.  
  225.     
  226.     def push(self, ns):
  227.         self.user_ns.update(ns)
  228.  
  229.     
  230.     def push_function(self, ns):
  231.         new_kwds = { }
  232.         for k, v in ns.iteritems():
  233.             if not isinstance(v, FunctionType):
  234.                 raise TypeError('function object expected')
  235.             isinstance(v, FunctionType)
  236.             new_kwds[k] = FunctionType(v.func_code, self.user_ns)
  237.         
  238.         self.user_ns.update(new_kwds)
  239.  
  240.     
  241.     def pack_exception(self, message, exc):
  242.         message['exception'] = exc.__class__
  243.         message['exception_value'] = traceback.format_exception_only(exc.__class__, exc)
  244.  
  245.     
  246.     def feed_block(self, source, filename = '<input>', symbol = 'single'):
  247.         self.message = self.setup_message()
  248.         
  249.         try:
  250.             code = self.command_compiler(source, filename, symbol)
  251.         except (OverflowError, SyntaxError, IndentationError, ValueError):
  252.             e = None
  253.             self.traceback_trap.args = sys.exc_info()
  254.             self.pack_exception(self.message, e)
  255.             return (COMPILER_ERROR, False)
  256.  
  257.         if code is None:
  258.             last_two = source.rsplit('\n', 2)[-2:]
  259.             print 'last two:', last_two
  260.             if len(last_two) == 2 and all((lambda .0: for s in .0:
  261. s.isspace())(last_two)):
  262.                 return (COMPLETE_INPUT, False)
  263.             return (INCOMPLETE_INPUT, True)
  264.         code is None
  265.         return (COMPLETE_INPUT, False)
  266.  
  267.     
  268.     def pull(self, keys):
  269.         if isinstance(keys, str):
  270.             result = self.user_ns.get(keys, NotDefined())
  271.             if isinstance(result, NotDefined):
  272.                 raise NameError('name %s is not defined' % keys)
  273.             isinstance(result, NotDefined)
  274.         elif isinstance(keys, (list, tuple)):
  275.             result = []
  276.             for key in keys:
  277.                 if not isinstance(key, str):
  278.                     raise TypeError('objects must be keyed by strings.')
  279.                 isinstance(key, str)
  280.                 r = self.user_ns.get(key, NotDefined())
  281.                 if isinstance(r, NotDefined):
  282.                     raise NameError('name %s is not defined' % key)
  283.                 isinstance(r, NotDefined)
  284.                 result.append(r)
  285.                 if len(keys) == 1:
  286.                     result = result[0]
  287.                     continue
  288.             
  289.         else:
  290.             raise TypeError('keys must be a strong or a list/tuple of strings')
  291.         return isinstance(keys, str)
  292.  
  293.     
  294.     def pull_function(self, keys):
  295.         return self.pull(keys)
  296.  
  297.     
  298.     def ipsystem(self, command):
  299.         command = self.var_expand(command)
  300.         system_shell(command, header = 'IPython system call: ', verbose = self.rc.system_verbose)
  301.  
  302.     
  303.     def ipmagic(self, arg_string):
  304.         raise NotImplementedError('Not ported yet')
  305.         args = arg_string.split(' ', 1)
  306.         magic_name = args[0]
  307.         magic_name = magic_name.lstrip(self.config.ESC_MAGIC)
  308.         
  309.         try:
  310.             magic_args = args[1]
  311.         except IndexError:
  312.             magic_args = ''
  313.  
  314.         fn = getattr(self.magic, 'magic_' + magic_name, None)
  315.         if fn is None:
  316.             self.error('Magic function `%s` not found.' % magic_name)
  317.         else:
  318.             magic_args = self.var_expand(magic_args)
  319.             return fn(magic_args)
  320.         return fn is None
  321.  
  322.     
  323.     def setup_message(self):
  324.         return dict(number = self.current_cell_number)
  325.  
  326.     
  327.     def setup_namespace(self):
  328.         self.user_ns.setdefault('__name__', '__main__')
  329.         self.user_ns.setdefault('__builtins__', __builtin__)
  330.         self.user_ns['__IP'] = self
  331.         if self.raw_input_builtin is not None:
  332.             self.user_ns['raw_input'] = self.raw_input_builtin
  333.         
  334.         if self.input_builtin is not None:
  335.             self.user_ns['input'] = self.input_builtin
  336.         
  337.         builtin_additions = dict(ipmagic = self.ipmagic)
  338.         __builtin__.__dict__.update(builtin_additions)
  339.         if self.history is not None:
  340.             self.history.setup_namespace(self.user_ns)
  341.         
  342.  
  343.     
  344.     def set_traps(self):
  345.         self.output_trap.set()
  346.         self.display_trap.set()
  347.         self.traceback_trap.set()
  348.  
  349.     
  350.     def unset_traps(self):
  351.         self.output_trap.unset()
  352.         self.display_trap.unset()
  353.         self.traceback_trap.unset()
  354.  
  355.     
  356.     def split_commands(self, python):
  357.         python = python.strip()
  358.         if isinstance(python, unicode):
  359.             python = '\xef\xbb\xbf' + python.encode('utf-8')
  360.         
  361.         ast = compiler.parse(python)
  362.         linenos = _[1]
  363.         linenos.append(None)
  364.         linenos[0] = 0
  365.         lines = python.splitlines()
  366.         cmds = []
  367.         for i, j in zip(linenos[:-1], linenos[1:]):
  368.             cmd = lines[i:j]
  369.             if cmd:
  370.                 cmds.append('\n'.join(cmd) + '\n')
  371.                 continue
  372.             []
  373.         
  374.         return cmds
  375.  
  376.     
  377.     def error(self, text):
  378.         errors = self.message.get('IPYTHON_ERROR', [])
  379.         errors.append(text)
  380.  
  381.     
  382.     def var_expand(self, template):
  383.         return str(ItplNS(template, self.user_ns))
  384.  
  385.     
  386.     def _possible_macro(self, obj):
  387.         if isinstance(obj, Macro):
  388.             self.execute_macro(obj)
  389.         
  390.  
  391.  
  392.