##// END OF EJS Templates
merge interactiveshell.py
MinRK -
Show More
@@ -22,12 +22,13 b' import __future__'
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
26 import new
25 import os
27 import os
26 import re
28 import re
27 import string
29 import string
28 import sys
30 import sys
29 import tempfile
31 import tempfile
30 import types
31 from contextlib import nested
32 from contextlib import nested
32
33
33 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
@@ -44,6 +45,7 b' from IPython.core.displayhook import DisplayHook'
44 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.history import HistoryManager
47 from IPython.core.inputlist import InputList
49 from IPython.core.inputlist import InputList
48 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.logger import Logger
51 from IPython.core.logger import Logger
@@ -101,7 +103,7 b' def softspace(file, newvalue):'
101
103
102 def no_op(*a, **kw): pass
104 def no_op(*a, **kw): pass
103
105
104 class SpaceInInput(Exception): pass
106 class SpaceInInput(exceptions.Exception): pass
105
107
106 class Bunch: pass
108 class Bunch: pass
107
109
@@ -215,6 +217,7 b' class InteractiveShell(Configurable, Magic):'
215 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
216 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
217 payload_manager = Instance('IPython.core.payload.PayloadManager')
219 payload_manager = Instance('IPython.core.payload.PayloadManager')
220 history_manager = Instance('IPython.core.history.HistoryManager')
218
221
219 # Private interface
222 # Private interface
220 _post_execute = set()
223 _post_execute = set()
@@ -260,7 +263,6 b' class InteractiveShell(Configurable, Magic):'
260 self.init_builtins()
263 self.init_builtins()
261
264
262 # pre_config_initialization
265 # pre_config_initialization
263 self.init_shadow_hist()
264
266
265 # The next section should contain everything that was in ipmaker.
267 # The next section should contain everything that was in ipmaker.
266 self.init_logstart()
268 self.init_logstart()
@@ -367,8 +369,9 b' class InteractiveShell(Configurable, Magic):'
367 # command compiler
369 # command compiler
368 self.compile = codeop.CommandCompiler()
370 self.compile = codeop.CommandCompiler()
369
371
370 # User input buffer
372 # User input buffers
371 self.buffer = []
373 self.buffer = []
374 self.buffer_raw = []
372
375
373 # Make an empty namespace, which extension writers can rely on both
376 # Make an empty namespace, which extension writers can rely on both
374 # existing and NEVER being used by ipython itself. This gives them a
377 # existing and NEVER being used by ipython itself. This gives them a
@@ -396,6 +399,9 b' class InteractiveShell(Configurable, Magic):'
396 # Indentation management
399 # Indentation management
397 self.indent_current_nsp = 0
400 self.indent_current_nsp = 0
398
401
402 # Increasing execution counter
403 self.execution_count = 1
404
399 def init_environment(self):
405 def init_environment(self):
400 """Any changes we need to make to the user's environment."""
406 """Any changes we need to make to the user's environment."""
401 pass
407 pass
@@ -424,11 +430,12 b' class InteractiveShell(Configurable, Magic):'
424 self.dir_stack = []
430 self.dir_stack = []
425
431
426 def init_logger(self):
432 def init_logger(self):
427 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
433 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
428 # local shortcut, this is used a LOT
434 logmode='rotate')
429 self.log = self.logger.log
430
435
431 def init_logstart(self):
436 def init_logstart(self):
437 """Initialize logging in case it was requested at the command line.
438 """
432 if self.logappend:
439 if self.logappend:
433 self.magic_logstart(self.logappend + ' append')
440 self.magic_logstart(self.logappend + ' append')
434 elif self.logfile:
441 elif self.logfile:
@@ -511,7 +518,7 b' class InteractiveShell(Configurable, Magic):'
511 def restore_sys_module_state(self):
518 def restore_sys_module_state(self):
512 """Restore the state of the sys module."""
519 """Restore the state of the sys module."""
513 try:
520 try:
514 for k, v in self._orig_sys_module_state.iteritems():
521 for k, v in self._orig_sys_module_state.items():
515 setattr(sys, k, v)
522 setattr(sys, k, v)
516 except AttributeError:
523 except AttributeError:
517 pass
524 pass
@@ -549,7 +556,7 b' class InteractiveShell(Configurable, Magic):'
549 # accepts it. Probably at least check that the hook takes the number
556 # accepts it. Probably at least check that the hook takes the number
550 # of args it's supposed to.
557 # of args it's supposed to.
551
558
552 f = types.MethodType(hook, self)
559 f = new.instancemethod(hook,self,self.__class__)
553
560
554 # check if the hook is for strdispatcher first
561 # check if the hook is for strdispatcher first
555 if str_key is not None:
562 if str_key is not None:
@@ -809,11 +816,8 b' class InteractiveShell(Configurable, Magic):'
809
816
810 # Similarly, track all namespaces where references can be held and that
817 # Similarly, track all namespaces where references can be held and that
811 # we can safely clear (so it can NOT include builtin). This one can be
818 # we can safely clear (so it can NOT include builtin). This one can be
812 # a simple list. Note that the main execution namespaces, user_ns and
819 # a simple list.
813 # user_global_ns, can NOT be listed here, as clearing them blindly
820 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
814 # causes errors in object __del__ methods. Instead, the reset() method
815 # clears them manually and carefully.
816 self.ns_refs_table = [ self.user_ns_hidden,
817 self.internal_ns, self._main_ns_cache ]
821 self.internal_ns, self._main_ns_cache ]
818
822
819 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
823 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
@@ -963,38 +967,25 b' class InteractiveShell(Configurable, Magic):'
963 # Finally, update the real user's namespace
967 # Finally, update the real user's namespace
964 self.user_ns.update(ns)
968 self.user_ns.update(ns)
965
969
966
967 def reset(self):
970 def reset(self):
968 """Clear all internal namespaces.
971 """Clear all internal namespaces.
969
972
970 Note that this is much more aggressive than %reset, since it clears
973 Note that this is much more aggressive than %reset, since it clears
971 fully all namespaces, as well as all input/output lists.
974 fully all namespaces, as well as all input/output lists.
972 """
975 """
973 self.alias_manager.clear_aliases()
976 # Clear histories
974
977 self.history_manager.reset()
975 # Clear input and output histories
976 self.input_hist[:] = []
977 self.input_hist_raw[:] = []
978 self.output_hist.clear()
979
978
980 # Clear namespaces holding user references
979 # Reset counter used to index all histories
980 self.execution_count = 0
981
982 # Restore the user namespaces to minimal usability
981 for ns in self.ns_refs_table:
983 for ns in self.ns_refs_table:
982 ns.clear()
984 ns.clear()
983
984 # The main execution namespaces must be cleared very carefully,
985 # skipping the deletion of the builtin-related keys, because doing so
986 # would cause errors in many object's __del__ methods.
987 for ns in [self.user_ns, self.user_global_ns]:
988 drop_keys = set(ns.keys())
989 drop_keys.discard('__builtin__')
990 drop_keys.discard('__builtins__')
991 for k in drop_keys:
992 del ns[k]
993
994 # Restore the user namespaces to minimal usability
995 self.init_user_ns()
985 self.init_user_ns()
996
986
997 # Restore the default and user aliases
987 # Restore the default and user aliases
988 self.alias_manager.clear_aliases()
998 self.alias_manager.init_aliases()
989 self.alias_manager.init_aliases()
999
990
1000 def reset_selective(self, regex=None):
991 def reset_selective(self, regex=None):
@@ -1218,61 +1209,21 b' class InteractiveShell(Configurable, Magic):'
1218 #-------------------------------------------------------------------------
1209 #-------------------------------------------------------------------------
1219
1210
1220 def init_history(self):
1211 def init_history(self):
1221 # List of input with multi-line handling.
1212 self.history_manager = HistoryManager(shell=self)
1222 self.input_hist = InputList()
1223 # This one will hold the 'raw' input history, without any
1224 # pre-processing. This will allow users to retrieve the input just as
1225 # it was exactly typed in by the user, with %hist -r.
1226 self.input_hist_raw = InputList()
1227
1228 # list of visited directories
1229 try:
1230 self.dir_hist = [os.getcwd()]
1231 except OSError:
1232 self.dir_hist = []
1233
1234 # dict of output history
1235 self.output_hist = {}
1236
1237 # Now the history file
1238 if self.profile:
1239 histfname = 'history-%s' % self.profile
1240 else:
1241 histfname = 'history'
1242 self.histfile = os.path.join(self.ipython_dir, histfname)
1243
1213
1244 # Fill the history zero entry, user counter starts at 1
1214 def save_hist(self):
1245 self.input_hist.append('\n')
1246 self.input_hist_raw.append('\n')
1247
1248 def init_shadow_hist(self):
1249 try:
1250 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1251 except UnicodeDecodeError:
1252 print "Your ipython_dir can't be decoded to unicode!"
1253 print "Please set HOME environment variable to something that"
1254 print r"only has ASCII characters, e.g. c:\home"
1255 print "Now it is", self.ipython_dir
1256 sys.exit()
1257 self.shadowhist = ipcorehist.ShadowHist(self.db)
1258
1259 def savehist(self):
1260 """Save input history to a file (via readline library)."""
1215 """Save input history to a file (via readline library)."""
1216 self.history_manager.save_hist()
1261
1217
1262 try:
1218 # For backwards compatibility
1263 self.readline.write_history_file(self.histfile)
1219 savehist = save_hist
1264 except:
1220
1265 print 'Unable to save IPython command history to file: ' + \
1221 def reload_hist(self):
1266 `self.histfile`
1267
1268 def reloadhist(self):
1269 """Reload the input history from disk file."""
1222 """Reload the input history from disk file."""
1223 self.history_manager.reload_hist()
1270
1224
1271 try:
1225 # For backwards compatibility
1272 self.readline.clear_history()
1226 reloadhist = reload_hist
1273 self.readline.read_history_file(self.shell.histfile)
1274 except AttributeError:
1275 pass
1276
1227
1277 def history_saving_wrapper(self, func):
1228 def history_saving_wrapper(self, func):
1278 """ Wrap func for readline history saving
1229 """ Wrap func for readline history saving
@@ -1286,62 +1237,13 b' class InteractiveShell(Configurable, Magic):'
1286 return func
1237 return func
1287
1238
1288 def wrapper():
1239 def wrapper():
1289 self.savehist()
1240 self.save_hist()
1290 try:
1241 try:
1291 func()
1242 func()
1292 finally:
1243 finally:
1293 readline.read_history_file(self.histfile)
1244 readline.read_history_file(self.histfile)
1294 return wrapper
1245 return wrapper
1295
1246
1296 def get_history(self, index=None, raw=False, output=True):
1297 """Get the history list.
1298
1299 Get the input and output history.
1300
1301 Parameters
1302 ----------
1303 index : n or (n1, n2) or None
1304 If n, then the last entries. If a tuple, then all in
1305 range(n1, n2). If None, then all entries. Raises IndexError if
1306 the format of index is incorrect.
1307 raw : bool
1308 If True, return the raw input.
1309 output : bool
1310 If True, then return the output as well.
1311
1312 Returns
1313 -------
1314 If output is True, then return a dict of tuples, keyed by the prompt
1315 numbers and with values of (input, output). If output is False, then
1316 a dict, keyed by the prompt number with the values of input. Raises
1317 IndexError if no history is found.
1318 """
1319 if raw:
1320 input_hist = self.input_hist_raw
1321 else:
1322 input_hist = self.input_hist
1323 if output:
1324 output_hist = self.user_ns['Out']
1325 n = len(input_hist)
1326 if index is None:
1327 start=0; stop=n
1328 elif isinstance(index, int):
1329 start=n-index; stop=n
1330 elif isinstance(index, tuple) and len(index) == 2:
1331 start=index[0]; stop=index[1]
1332 else:
1333 raise IndexError('Not a valid index for the input history: %r'
1334 % index)
1335 hist = {}
1336 for i in range(start, stop):
1337 if output:
1338 hist[i] = (input_hist[i], output_hist.get(i))
1339 else:
1340 hist[i] = input_hist[i]
1341 if len(hist)==0:
1342 raise IndexError('No history for range of indices: %r' % index)
1343 return hist
1344
1345 #-------------------------------------------------------------------------
1247 #-------------------------------------------------------------------------
1346 # Things related to exception handling and tracebacks (not debugging)
1248 # Things related to exception handling and tracebacks (not debugging)
1347 #-------------------------------------------------------------------------
1249 #-------------------------------------------------------------------------
@@ -1373,7 +1275,7 b' class InteractiveShell(Configurable, Magic):'
1373
1275
1374 Set a custom exception handler, which will be called if any of the
1276 Set a custom exception handler, which will be called if any of the
1375 exceptions in exc_tuple occur in the mainloop (specifically, in the
1277 exceptions in exc_tuple occur in the mainloop (specifically, in the
1376 runcode() method.
1278 run_code() method.
1377
1279
1378 Inputs:
1280 Inputs:
1379
1281
@@ -1413,7 +1315,7 b' class InteractiveShell(Configurable, Magic):'
1413
1315
1414 if handler is None: handler = dummy_handler
1316 if handler is None: handler = dummy_handler
1415
1317
1416 self.CustomTB = types.MethodType(handler, self)
1318 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1417 self.custom_exceptions = exc_tuple
1319 self.custom_exceptions = exc_tuple
1418
1320
1419 def excepthook(self, etype, value, tb):
1321 def excepthook(self, etype, value, tb):
@@ -1568,8 +1470,8 b' class InteractiveShell(Configurable, Magic):'
1568 self.has_readline = False
1470 self.has_readline = False
1569 self.readline = None
1471 self.readline = None
1570 # Set a number of methods that depend on readline to be no-op
1472 # Set a number of methods that depend on readline to be no-op
1571 self.savehist = no_op
1473 self.save_hist = no_op
1572 self.reloadhist = no_op
1474 self.reload_hist = no_op
1573 self.set_readline_completer = no_op
1475 self.set_readline_completer = no_op
1574 self.set_custom_completer = no_op
1476 self.set_custom_completer = no_op
1575 self.set_completer_frame = no_op
1477 self.set_completer_frame = no_op
@@ -1631,7 +1533,7 b' class InteractiveShell(Configurable, Magic):'
1631
1533
1632 # If we have readline, we want our history saved upon ipython
1534 # If we have readline, we want our history saved upon ipython
1633 # exiting.
1535 # exiting.
1634 atexit.register(self.savehist)
1536 atexit.register(self.save_hist)
1635
1537
1636 # Configure auto-indent for all platforms
1538 # Configure auto-indent for all platforms
1637 self.set_autoindent(self.autoindent)
1539 self.set_autoindent(self.autoindent)
@@ -1663,7 +1565,8 b' class InteractiveShell(Configurable, Magic):'
1663
1565
1664 def _indent_current_str(self):
1566 def _indent_current_str(self):
1665 """return the current level of indentation as a string"""
1567 """return the current level of indentation as a string"""
1666 return self.indent_current_nsp * ' '
1568 #return self.indent_current_nsp * ' '
1569 return self.input_splitter.indent_spaces * ' '
1667
1570
1668 #-------------------------------------------------------------------------
1571 #-------------------------------------------------------------------------
1669 # Things related to text completion
1572 # Things related to text completion
@@ -1755,7 +1658,8 b' class InteractiveShell(Configurable, Magic):'
1755 The position argument (defaults to 0) is the index in the completers
1658 The position argument (defaults to 0) is the index in the completers
1756 list where you want the completer to be inserted."""
1659 list where you want the completer to be inserted."""
1757
1660
1758 newcomp = types.MethodType(completer, self.Completer)
1661 newcomp = new.instancemethod(completer,self.Completer,
1662 self.Completer.__class__)
1759 self.Completer.matchers.insert(pos,newcomp)
1663 self.Completer.matchers.insert(pos,newcomp)
1760
1664
1761 def set_readline_completer(self):
1665 def set_readline_completer(self):
@@ -1826,11 +1730,12 b' class InteractiveShell(Configurable, Magic):'
1826 print 'Magic function. Passed parameter is between < >:'
1730 print 'Magic function. Passed parameter is between < >:'
1827 print '<%s>' % parameter_s
1731 print '<%s>' % parameter_s
1828 print 'The self object is:',self
1732 print 'The self object is:',self
1829 newcomp = types.MethodType(completer, self.Completer)
1733
1830 self.define_magic('foo',foo_impl)
1734 self.define_magic('foo',foo_impl)
1831 """
1735 """
1832
1736
1833 im = types.MethodType(func, self)
1737 import new
1738 im = new.instancemethod(func,self, self.__class__)
1834 old = getattr(self, "magic_" + magicname, None)
1739 old = getattr(self, "magic_" + magicname, None)
1835 setattr(self, "magic_" + magicname, im)
1740 setattr(self, "magic_" + magicname, im)
1836 return old
1741 return old
@@ -1941,7 +1846,6 b' class InteractiveShell(Configurable, Magic):'
1941 # code out there that may rely on this).
1846 # code out there that may rely on this).
1942 self.prefilter = self.prefilter_manager.prefilter_lines
1847 self.prefilter = self.prefilter_manager.prefilter_lines
1943
1848
1944
1945 def auto_rewrite_input(self, cmd):
1849 def auto_rewrite_input(self, cmd):
1946 """Print to the screen the rewritten form of the user's command.
1850 """Print to the screen the rewritten form of the user's command.
1947
1851
@@ -2128,12 +2032,11 b' class InteractiveShell(Configurable, Magic):'
2128 with prepended_to_syspath(dname):
2032 with prepended_to_syspath(dname):
2129 try:
2033 try:
2130 with open(fname) as thefile:
2034 with open(fname) as thefile:
2131 script = thefile.read()
2035 # self.run_cell currently captures all exceptions
2132 # self.runlines currently captures all exceptions
2036 # raised in user code. It would be nice if there were
2133 # raise in user code. It would be nice if there were
2134 # versions of runlines, execfile that did raise, so
2037 # versions of runlines, execfile that did raise, so
2135 # we could catch the errors.
2038 # we could catch the errors.
2136 self.runlines(script, clean=True)
2039 self.run_cell(thefile.read())
2137 except:
2040 except:
2138 self.showtraceback()
2041 self.showtraceback()
2139 warn('Unknown failure executing file: <%s>' % fname)
2042 warn('Unknown failure executing file: <%s>' % fname)
@@ -2178,8 +2081,8 b' class InteractiveShell(Configurable, Magic):'
2178 # the main object).
2081 # the main object).
2179 # - do any logging of input
2082 # - do any logging of input
2180 # - update histories (raw/translated)
2083 # - update histories (raw/translated)
2181 # - then, call plain runsource (for single blocks, so displayhook is
2084 # - then, call plain run_source (for single blocks, so displayhook is
2182 # triggered) or runcode (for multiline blocks in exec mode).
2085 # triggered) or run_code (for multiline blocks in exec mode).
2183 #
2086 #
2184 # Once this is done, we'll be able to stop using runlines and we'll
2087 # Once this is done, we'll be able to stop using runlines and we'll
2185 # also have a much cleaner separation of logging, input history and
2088 # also have a much cleaner separation of logging, input history and
@@ -2192,34 +2095,91 b' class InteractiveShell(Configurable, Magic):'
2192
2095
2193 if not blocks:
2096 if not blocks:
2194 return
2097 return
2195
2196 # Single-block input should behave like an interactive prompt
2197 if len(blocks) == 1:
2198 self.runlines(blocks[0])
2199 return
2200
2098
2201 # In multi-block input, if the last block is a simple (one-two lines)
2099 # Store the 'ipython' version of the cell as well, since that's what
2202 # expression, run it in single mode so it produces output. Otherwise
2100 # needs to go into the translated history and get executed (the
2203 # just feed the whole thing to runcode.
2101 # original cell may contain non-python syntax).
2204 # This seems like a reasonable usability design.
2102 ipy_cell = ''.join(blocks)
2205 last = blocks[-1]
2103
2206
2104 # Store raw and processed history
2207 # Note: below, whenever we call runcode, we must sync history
2105 self.history_manager.store_inputs(ipy_cell, cell)
2208 # ourselves, because runcode is NOT meant to manage history at all.
2106
2209 if len(last.splitlines()) < 2:
2107 self.logger.log(ipy_cell, cell)
2210 # Get the main body to run as a cell
2108 # dbg code!!!
2211 body = ''.join(blocks[:-1])
2109 if 0:
2212 self.input_hist.append(body)
2110 def myapp(self, val): # dbg
2213 self.input_hist_raw.append(body)
2111 import traceback as tb
2214 retcode = self.runcode(body, post_execute=False)
2112 stack = ''.join(tb.format_stack())
2215 if retcode==0:
2113 print 'Value:', val
2216 # And the last expression via runlines so it produces output
2114 print 'Stack:\n', stack
2217 self.runlines(last)
2115 list.append(self, val)
2116
2117 import new
2118 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2119 list)
2120 # End dbg
2121
2122 # All user code execution must happen with our context managers active
2123 with nested(self.builtin_trap, self.display_trap):
2124
2125 # Single-block input should behave like an interactive prompt
2126 if len(blocks) == 1:
2127 # since we return here, we need to update the execution count
2128 out = self.run_one_block(blocks[0])
2129 self.execution_count += 1
2130 return out
2131
2132 # In multi-block input, if the last block is a simple (one-two
2133 # lines) expression, run it in single mode so it produces output.
2134 # Otherwise just feed the whole thing to run_code. This seems like
2135 # a reasonable usability design.
2136 last = blocks[-1]
2137 last_nlines = len(last.splitlines())
2138
2139 # Note: below, whenever we call run_code, we must sync history
2140 # ourselves, because run_code is NOT meant to manage history at all.
2141 if last_nlines < 2:
2142 # Here we consider the cell split between 'body' and 'last',
2143 # store all history and execute 'body', and if successful, then
2144 # proceed to execute 'last'.
2145
2146 # Get the main body to run as a cell
2147 ipy_body = ''.join(blocks[:-1])
2148 retcode = self.run_code(ipy_body, post_execute=False)
2149 if retcode==0:
2150 # And the last expression via runlines so it produces output
2151 self.run_one_block(last)
2152 else:
2153 # Run the whole cell as one entity, storing both raw and
2154 # processed input in history
2155 self.run_code(ipy_cell)
2156
2157 # Each cell is a *single* input, regardless of how many lines it has
2158 self.execution_count += 1
2159
2160 def run_one_block(self, block):
2161 """Run a single interactive block.
2162
2163 If the block is single-line, dynamic transformations are applied to it
2164 (like automagics, autocall and alias recognition).
2165 """
2166 if len(block.splitlines()) <= 1:
2167 out = self.run_single_line(block)
2218 else:
2168 else:
2219 # Run the whole cell as one entity
2169 out = self.run_code(block)
2220 self.input_hist.append(cell)
2170 return out
2221 self.input_hist_raw.append(cell)
2171
2222 self.runcode(cell)
2172 def run_single_line(self, line):
2173 """Run a single-line interactive statement.
2174
2175 This assumes the input has been transformed to IPython syntax by
2176 applying all static transformations (those with an explicit prefix like
2177 % or !), but it will further try to apply the dynamic ones.
2178
2179 It does not update history.
2180 """
2181 tline = self.prefilter_manager.prefilter_line(line)
2182 return self.run_source(tline)
2223
2183
2224 def runlines(self, lines, clean=False):
2184 def runlines(self, lines, clean=False):
2225 """Run a string of one or more lines of source.
2185 """Run a string of one or more lines of source.
@@ -2238,9 +2198,15 b' class InteractiveShell(Configurable, Magic):'
2238
2198
2239 # We must start with a clean buffer, in case this is run from an
2199 # We must start with a clean buffer, in case this is run from an
2240 # interactive IPython session (via a magic, for example).
2200 # interactive IPython session (via a magic, for example).
2241 self.resetbuffer()
2201 self.reset_buffer()
2242 lines = lines.splitlines()
2202 lines = lines.splitlines()
2243 more = 0
2203
2204 # Since we will prefilter all lines, store the user's raw input too
2205 # before we apply any transformations
2206 self.buffer_raw[:] = [ l+'\n' for l in lines]
2207
2208 more = False
2209 prefilter_lines = self.prefilter_manager.prefilter_lines
2244 with nested(self.builtin_trap, self.display_trap):
2210 with nested(self.builtin_trap, self.display_trap):
2245 for line in lines:
2211 for line in lines:
2246 # skip blank lines so we don't mess up the prompt counter, but
2212 # skip blank lines so we don't mess up the prompt counter, but
@@ -2248,25 +2214,19 b' class InteractiveShell(Configurable, Magic):'
2248 # is true)
2214 # is true)
2249
2215
2250 if line or more:
2216 if line or more:
2251 # push to raw history, so hist line numbers stay in sync
2217 more = self.push_line(prefilter_lines(line, more))
2252 self.input_hist_raw.append(line + '\n')
2218 # IPython's run_source returns None if there was an error
2253 prefiltered = self.prefilter_manager.prefilter_lines(line,
2254 more)
2255 more = self.push_line(prefiltered)
2256 # IPython's runsource returns None if there was an error
2257 # compiling the code. This allows us to stop processing
2219 # compiling the code. This allows us to stop processing
2258 # right away, so the user gets the error message at the
2220 # right away, so the user gets the error message at the
2259 # right place.
2221 # right place.
2260 if more is None:
2222 if more is None:
2261 break
2223 break
2262 else:
2263 self.input_hist_raw.append("\n")
2264 # final newline in case the input didn't have it, so that the code
2224 # final newline in case the input didn't have it, so that the code
2265 # actually does get executed
2225 # actually does get executed
2266 if more:
2226 if more:
2267 self.push_line('\n')
2227 self.push_line('\n')
2268
2228
2269 def runsource(self, source, filename='<input>', symbol='single'):
2229 def run_source(self, source, filename='<ipython console>', symbol='single'):
2270 """Compile and run some source in the interpreter.
2230 """Compile and run some source in the interpreter.
2271
2231
2272 Arguments are as for compile_command().
2232 Arguments are as for compile_command().
@@ -2281,7 +2241,7 b' class InteractiveShell(Configurable, Magic):'
2281 compile_command() returned None. Nothing happens.
2241 compile_command() returned None. Nothing happens.
2282
2242
2283 3) The input is complete; compile_command() returned a code
2243 3) The input is complete; compile_command() returned a code
2284 object. The code is executed by calling self.runcode() (which
2244 object. The code is executed by calling self.run_code() (which
2285 also handles run-time exceptions, except for SystemExit).
2245 also handles run-time exceptions, except for SystemExit).
2286
2246
2287 The return value is:
2247 The return value is:
@@ -2299,14 +2259,6 b' class InteractiveShell(Configurable, Magic):'
2299 if type(source)==str:
2259 if type(source)==str:
2300 source = source.decode(self.stdin_encoding)
2260 source = source.decode(self.stdin_encoding)
2301
2261
2302 # if the source code has leading blanks, add 'if 1:\n' to it
2303 # this allows execution of indented pasted code. It is tempting
2304 # to add '\n' at the end of source to run commands like ' a=1'
2305 # directly, but this fails for more complicated scenarios
2306
2307 if source[:1] in [' ', '\t']:
2308 source = u'if 1:\n%s' % source
2309
2310 try:
2262 try:
2311 code = self.compile(source,filename,symbol)
2263 code = self.compile(source,filename,symbol)
2312 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2264 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
@@ -2325,12 +2277,15 b' class InteractiveShell(Configurable, Magic):'
2325 # buffer attribute as '\n'.join(self.buffer).
2277 # buffer attribute as '\n'.join(self.buffer).
2326 self.code_to_run = code
2278 self.code_to_run = code
2327 # now actually execute the code object
2279 # now actually execute the code object
2328 if self.runcode(code) == 0:
2280 if self.run_code(code) == 0:
2329 return False
2281 return False
2330 else:
2282 else:
2331 return None
2283 return None
2332
2284
2333 def runcode(self, code_obj, post_execute=True):
2285 # For backwards compatibility
2286 runsource = run_source
2287
2288 def run_code(self, code_obj, post_execute=True):
2334 """Execute a code object.
2289 """Execute a code object.
2335
2290
2336 When an exception occurs, self.showtraceback() is called to display a
2291 When an exception occurs, self.showtraceback() is called to display a
@@ -2353,14 +2308,14 b' class InteractiveShell(Configurable, Magic):'
2353 outflag = 1 # happens in more places, so it's easier as default
2308 outflag = 1 # happens in more places, so it's easier as default
2354 try:
2309 try:
2355 try:
2310 try:
2356 self.hooks.pre_runcode_hook()
2311 self.hooks.pre_run_code_hook()
2357 #rprint('Running code') # dbg
2312 #rprint('Running code') # dbg
2358 exec code_obj in self.user_global_ns, self.user_ns
2313 exec code_obj in self.user_global_ns, self.user_ns
2359 finally:
2314 finally:
2360 # Reset our crash handler in place
2315 # Reset our crash handler in place
2361 sys.excepthook = old_excepthook
2316 sys.excepthook = old_excepthook
2362 except SystemExit:
2317 except SystemExit:
2363 self.resetbuffer()
2318 self.reset_buffer()
2364 self.showtraceback(exception_only=True)
2319 self.showtraceback(exception_only=True)
2365 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2320 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2366 except self.custom_exceptions:
2321 except self.custom_exceptions:
@@ -2393,18 +2348,21 b' class InteractiveShell(Configurable, Magic):'
2393 self.code_to_run = None
2348 self.code_to_run = None
2394 return outflag
2349 return outflag
2395
2350
2351 # For backwards compatibility
2352 runcode = run_code
2353
2396 def push_line(self, line):
2354 def push_line(self, line):
2397 """Push a line to the interpreter.
2355 """Push a line to the interpreter.
2398
2356
2399 The line should not have a trailing newline; it may have
2357 The line should not have a trailing newline; it may have
2400 internal newlines. The line is appended to a buffer and the
2358 internal newlines. The line is appended to a buffer and the
2401 interpreter's runsource() method is called with the
2359 interpreter's run_source() method is called with the
2402 concatenated contents of the buffer as source. If this
2360 concatenated contents of the buffer as source. If this
2403 indicates that the command was executed or invalid, the buffer
2361 indicates that the command was executed or invalid, the buffer
2404 is reset; otherwise, the command is incomplete, and the buffer
2362 is reset; otherwise, the command is incomplete, and the buffer
2405 is left as it was after the line was appended. The return
2363 is left as it was after the line was appended. The return
2406 value is 1 if more input is required, 0 if the line was dealt
2364 value is 1 if more input is required, 0 if the line was dealt
2407 with in some way (this is the same as runsource()).
2365 with in some way (this is the same as run_source()).
2408 """
2366 """
2409
2367
2410 # autoindent management should be done here, and not in the
2368 # autoindent management should be done here, and not in the
@@ -2413,17 +2371,24 b' class InteractiveShell(Configurable, Magic):'
2413 # push).
2371 # push).
2414
2372
2415 #print 'push line: <%s>' % line # dbg
2373 #print 'push line: <%s>' % line # dbg
2416 for subline in line.splitlines():
2417 self._autoindent_update(subline)
2418 self.buffer.append(line)
2374 self.buffer.append(line)
2419 more = self.runsource('\n'.join(self.buffer), self.filename)
2375 full_source = '\n'.join(self.buffer)
2376 more = self.run_source(full_source, self.filename)
2420 if not more:
2377 if not more:
2421 self.resetbuffer()
2378 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2379 full_source)
2380 self.reset_buffer()
2381 self.execution_count += 1
2422 return more
2382 return more
2423
2383
2424 def resetbuffer(self):
2384 def reset_buffer(self):
2425 """Reset the input buffer."""
2385 """Reset the input buffer."""
2426 self.buffer[:] = []
2386 self.buffer[:] = []
2387 self.buffer_raw[:] = []
2388 self.input_splitter.reset()
2389
2390 # For backwards compatibility
2391 resetbuffer = reset_buffer
2427
2392
2428 def _is_secondary_block_start(self, s):
2393 def _is_secondary_block_start(self, s):
2429 if not s.endswith(':'):
2394 if not s.endswith(':'):
@@ -2462,24 +2427,6 b' class InteractiveShell(Configurable, Magic):'
2462
2427
2463 return '\n'.join(res) + '\n'
2428 return '\n'.join(res) + '\n'
2464
2429
2465 def _autoindent_update(self,line):
2466 """Keep track of the indent level."""
2467
2468 #debugx('line')
2469 #debugx('self.indent_current_nsp')
2470 if self.autoindent:
2471 if line:
2472 inisp = num_ini_spaces(line)
2473 if inisp < self.indent_current_nsp:
2474 self.indent_current_nsp = inisp
2475
2476 if line[-1] == ':':
2477 self.indent_current_nsp += 4
2478 elif dedent_re.match(line):
2479 self.indent_current_nsp -= 4
2480 else:
2481 self.indent_current_nsp = 0
2482
2483 #-------------------------------------------------------------------------
2430 #-------------------------------------------------------------------------
2484 # Things related to GUI support and pylab
2431 # Things related to GUI support and pylab
2485 #-------------------------------------------------------------------------
2432 #-------------------------------------------------------------------------
General Comments 0
You need to be logged in to leave comments. Login now