##// END OF EJS Templates
Add Trove classifiers for PyPI.
Add Trove classifiers for PyPI.

File last commit:

r4739:c7f7b482
r4771:a88bf200
Show More
history.py
831 lines | 30.4 KiB | text/x-python | PythonLexer
vivainio
crlf normalization
r851 """ History related magics and functionality """
Fernando Perez
Created HistoryManager to better organize history control....
r3079 #-----------------------------------------------------------------------------
# Copyright (C) 2010 The IPython Development Team.
#
# Distributed under the terms of the BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
vivainio
crlf normalization
r851
fperez
Add -f flag to %history to direct output to file
r960 # Stdlib imports
Thomas Kluyver
Put history saving into a separate thread.
r3711 import atexit
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 import datetime
fperez
Add -f flag to %history to direct output to file
r960 import os
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 import re
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 import sqlite3
Thomas Kluyver
Put history saving into a separate thread.
r3711 import threading
fperez
Add -f flag to %history to direct output to file
r960
Fernando Perez
Created HistoryManager to better organize history control....
r3079 # Our own packages
Thomas Kluyver
Make HistoryManager configurable.
r3393 from IPython.config.configurable import Configurable
Fernando Perez
Created HistoryManager to better organize history control....
r3079
Thomas Kluyver
Move skip_doctest decorator to separate module, so that it can be used without triggering other imports.
r3886 from IPython.testing.skipdoctest import skip_doctest
MinRK
io.Term.cin/out/err replaced by io.stdin/out/err...
r3800 from IPython.utils import io
Thomas Kluyver
Use casting trait for session number in history, so IPython will start on PyPy....
r4661 from IPython.utils.traitlets import Bool, Dict, Instance, Int, CInt, List, Unicode
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils.warn import warn
Fernando Perez
Created HistoryManager to better organize history control....
r3079
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
Thomas Kluyver
Make HistoryManager configurable.
r3393 class HistoryManager(Configurable):
Fernando Perez
Created HistoryManager to better organize history control....
r3079 """A class to organize all history-related functionality in one place.
"""
Fernando Perez
Document object interface to HistoryManger according to our conventions....
r3095 # Public interface
# An instance of the IPython shell we are attached to
Thomas Kluyver
Make HistoryManager configurable.
r3393 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
# Lists to hold processed and raw history. These start with a blank entry
# so that we can index them starting from 1
input_hist_parsed = List([""])
input_hist_raw = List([""])
Fernando Perez
Document object interface to HistoryManger according to our conventions....
r3095 # A list of directories visited during session
Thomas Kluyver
Make HistoryManager configurable.
r3393 dir_hist = List()
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 def _dir_hist_default(self):
try:
Jörgen Stenarson
Search of getcwd and replace with getcwdu. Ignoring core/prompts.py
r4208 return [os.getcwdu()]
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 except OSError:
return []
Thomas Kluyver
Separate 'Out' in user_ns from the output history logging.
r3417 # A dict of output history, keyed with ints from the shell's
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 # execution count.
Thomas Kluyver
Separate 'Out' in user_ns from the output history logging.
r3417 output_hist = Dict()
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 # The text/plain repr of outputs.
output_hist_reprs = Dict()
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465
Thomas Kluyver
Make HistoryManager configurable.
r3393 # String holding the path to the history file
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 hist_file = Unicode(config=True)
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 # The SQLite database
Thomas Kluyver
Make HistoryManager configurable.
r3393 db = Instance(sqlite3.Connection)
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 # The number of the current session in the history database
Thomas Kluyver
Use casting trait for session number in history, so IPython will start on PyPy....
r4661 session_number = CInt()
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391 # Should we log output to the database? (default no)
Thomas Kluyver
Make HistoryManager configurable.
r3393 db_log_output = Bool(False, config=True)
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391 # Write to database every x commands (higher values save disk access & power)
# Values of 1 or less effectively disable caching.
Thomas Kluyver
Make HistoryManager configurable.
r3393 db_cache_size = Int(0, config=True)
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391 # The input and output caches
Thomas Kluyver
Make HistoryManager configurable.
r3393 db_input_cache = List()
db_output_cache = List()
Thomas Kluyver
Small changes as suggested by Fernando.
r3382
Thomas Kluyver
Put history saving into a separate thread.
r3711 # History saving in separate thread
save_thread = Instance('IPython.core.history.HistorySavingThread')
Thomas Kluyver
Fix in preparation for Python 3.3 compatibility....
r4739 try: # Event is a function returning an instance of _Event...
save_flag = Instance(threading._Event)
except AttributeError: # ...until Python 3.3, when it's a class.
save_flag = Instance(threading.Event)
Thomas Kluyver
Put history saving into a separate thread.
r3711
Fernando Perez
Document object interface to HistoryManger according to our conventions....
r3095 # Private interface
# Variables used to store the three last inputs from the user. On each new
# history update, we populate the user's namespace with these, shifted as
# necessary.
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 _i00 = Unicode(u'')
_i = Unicode(u'')
_ii = Unicode(u'')
_iii = Unicode(u'')
Fernando Perez
Small fix and cleanup for exit/quit command filtering.
r3246
Thomas Kluyver
Replace exit command set with regex.
r3750 # A regex matching all forms of the exit command, so that we don't store
# them in the history (it's annoying to rewind the first entry and land on
# an exit call).
_exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465
def __init__(self, shell, config=None, **traits):
Fernando Perez
Created HistoryManager to better organize history control....
r3079 """Create a new history manager associated with a shell instance.
"""
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087 # We need a pointer back to the shell for various tasks.
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 super(HistoryManager, self).__init__(shell=shell, config=config,
**traits)
if self.hist_file == u'':
# No one has set the hist_file, yet.
MinRK
Terminal IPython working with newapp
r3963 histfname = 'history'
self.hist_file = os.path.join(shell.profile_dir.location, histfname + '.sqlite')
Fernando Perez
Created HistoryManager to better organize history control....
r3079
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 try:
self.init_db()
except sqlite3.DatabaseError:
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 if os.path.isfile(self.hist_file):
# Try to move the file out of the way.
MinRK
Terminal IPython working with newapp
r3963 newpath = os.path.join(self.shell.profile_dir.location, "hist-corrupt.sqlite")
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465 os.rename(self.hist_file, newpath)
print("ERROR! History file wasn't a valid SQLite database.",
"It was moved to %s" % newpath, "and a new file created.")
self.init_db()
else:
# The hist_file is probably :memory: or something else.
raise
Thomas Kluyver
Put history saving into a separate thread.
r3711
self.save_flag = threading.Event()
Thomas Kluyver
Add locks for input and output caches.
r3713 self.db_input_cache_lock = threading.Lock()
self.db_output_cache_lock = threading.Lock()
Thomas Kluyver
Put history saving into a separate thread.
r3711 self.save_thread = HistorySavingThread(self)
self.save_thread.start()
Robert Kern
BUG: use a :memory: history DB for testing. Refactor the initialization of the HistoryManager to support this.
r3465
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 self.new_session()
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 def init_db(self):
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 """Connect to the database, and create tables if necessary."""
MinRK
add get_session_info to HistoryManager for querying session table...
r4487 # use detect_types so that timestamps return datetime objects
self.db = sqlite3.connect(self.hist_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
primary key autoincrement, start timestamp,
end timestamp, num_cmds integer, remark text)""")
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391 self.db.execute("""CREATE TABLE IF NOT EXISTS history
(session integer, line integer, source text, source_raw text,
PRIMARY KEY (session, line))""")
# Output history is optional, but ensure the table's there so it can be
# enabled later.
self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
(session integer, line integer, output text,
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 PRIMARY KEY (session, line))""")
self.db.commit()
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401
Thomas Kluyver
new_session can be called from either thread.
r3714 def new_session(self, conn=None):
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 """Get a new session number."""
Thomas Kluyver
new_session can be called from either thread.
r3714 if conn is None:
conn = self.db
with conn:
cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 NULL, "") """, (datetime.datetime.now(),))
self.session_number = cur.lastrowid
def end_session(self):
"""Close the database session, filling in the end time and line count."""
self.writeout_cache()
with self.db:
self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
session==?""", (datetime.datetime.now(),
len(self.input_hist_parsed)-1, self.session_number))
self.session_number = 0
def name_session(self, name):
"""Give the current session a name in the history database."""
with self.db:
self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
(name, self.session_number))
def reset(self, new_session=True):
"""Clear the session history, releasing all object references, and
optionally open a new session."""
self.output_hist.clear()
# The directory history can't be completely empty
Jörgen Stenarson
Search of getcwd and replace with getcwdu. Ignoring core/prompts.py
r4208 self.dir_hist[:] = [os.getcwdu()]
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405
if new_session:
Thomas Kluyver
%reset doesn't reset prompt number.
r3703 if self.session_number:
self.end_session()
self.input_hist_parsed[:] = [""]
self.input_hist_raw[:] = [""]
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405 self.new_session()
## -------------------------------
## Methods for retrieving history:
## -------------------------------
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def _run_sql(self, sql, params, raw=True, output=False):
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 """Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (to replace "?")
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 raw, output : bool
See :meth:`get_range`
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401
Returns
-------
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 Tuples as :meth:`get_range`
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 """
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 toget = 'source_raw' if raw else 'source'
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 sqlfrom = "history"
if output:
sqlfrom = "history LEFT JOIN output_history USING (session, line)"
toget = "history.%s, output_history.output" % toget
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
(toget, sqlfrom) + sql, params)
Thomas Kluyver
Allow history to store multiple outputs for a single input line.
r3415 if output: # Regroup into 3-tuples, and parse JSON
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 return cur
MinRK
add get_session_info to HistoryManager for querying session table...
r4487 def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
-------
(session_id [int], start [datetime], end [datetime], num_cmds [int], remark [unicode])
Sessions that are running or did not exit cleanly will have `end=None`
and `num_cmds=None`.
"""
if session <= 0:
session += self.session_number
query = "SELECT * from sessions where session == ?"
return self.db.execute(query, (session,)).fetchone()
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
Thomas Kluyver
Further refinements to history interfaces.
r3420 """Get the last n lines from the history database.
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 Parameters
----------
n : int
The number of lines to get
raw, output : bool
See :meth:`get_range`
include_latest : bool
If False (default), n+1 lines are fetched, and the latest one
is discarded. This is intended to be used where the function
is called by a user command, which it should not return.
Returns
-------
Tuples as :meth:`get_range`
"""
Thomas Kluyver
Flush cache before querying database.
r3403 self.writeout_cache()
Thomas Kluyver
Further refinements to history interfaces.
r3420 if not include_latest:
n += 1
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 (n,), raw=raw, output=output)
Thomas Kluyver
Further refinements to history interfaces.
r3420 if not include_latest:
return reversed(list(cur)[1:])
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 return reversed(list(cur))
Satrajit Ghosh
History refactored and saved to json file...
r3240
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def search(self, pattern="*", raw=True, search_raw=True,
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 output=False):
Thomas Kluyver
Further refinements to history interfaces.
r3420 """Search the database using unix glob-style matching (wildcards
* and ?).
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 Parameters
----------
pattern : str
The wildcarded pattern to match when searching
search_raw : bool
If True, search the raw input, otherwise, the parsed input
raw, output : bool
See :meth:`get_range`
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 Returns
-------
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 Tuples as :meth:`get_range`
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 """
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 tosearch = "source_raw" if search_raw else "source"
Thomas Kluyver
Simplify magic_history display code, allow get_hist_search to include output in return values, and add some unit tests.
r3400 if output:
tosearch = "history." + tosearch
Thomas Kluyver
Flush cache before querying database.
r3403 self.writeout_cache()
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 raw=raw, output=output)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 """Get input and output history from the current session. Called by
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 get_range, and takes similar parameters."""
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380
Fernando Perez
Created HistoryManager to better organize history control....
r3079 n = len(input_hist)
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 if start < 0:
start += n
if not stop:
stop = n
elif stop < 0:
stop += n
Fernando Perez
Created HistoryManager to better organize history control....
r3079 for i in range(start, stop):
if output:
Thomas Kluyver
Separate 'Out' in user_ns from the output history logging.
r3417 line = (input_hist[i], self.output_hist_reprs.get(i))
Fernando Perez
Created HistoryManager to better organize history control....
r3079 else:
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 line = input_hist[i]
yield (0, i, line)
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 """Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
start : int
First line to retrieve.
stop : int
Thomas Kluyver
Passing IPython.core tests.
r3396 End of line range (excluded from output itself). If None, retrieve
to the end of the session.
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True.
"""
if session == 0 or session==self.session_number: # Current session
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 return self._get_range_session(start, stop, raw, output)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 if session < 0:
session += self.session_number
if stop:
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 lineclause = "line >= ? AND line < ?"
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 params = (session, start, stop)
else:
lineclause = "line>=?"
params = (session, start)
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 return self._run_sql("WHERE session==? AND %s""" % lineclause,
Thomas Kluyver
Simplify history retrieval code by moving query building and running into a common helper function.
r3401 params, raw=raw, output=output)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 def get_range_by_str(self, rangestr, raw=True, output=False):
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 """Get lines of history from a string of ranges, as used by magic
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 commands %hist, %save, %macro, etc.
Parameters
----------
rangestr : str
A string specifying ranges, e.g. "5 ~2/1-4". See
:func:`magic_history` for full details.
raw, output : bool
As :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 for sess, s, e in extract_hist_ranges(rangestr):
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 for line in self.get_range(sess, s, e, raw=raw, output=output):
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 yield line
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405
## ----------------------------
## Methods for storing history:
## ----------------------------
Thomas Kluyver
Tidy up store_inputs
r3390 def store_inputs(self, line_num, source, source_raw=None):
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087 """Store source and raw input in history and create input cache
variables _i*.
Fernando Perez
Add support for accessing raw data to inputsplitter....
r3080 Parameters
----------
Thomas Kluyver
Tidy up store_inputs
r3390 line_num : int
The prompt number of this input.
Fernando Perez
Add support for accessing raw data to inputsplitter....
r3080 source : str
Python input.
source_raw : str, optional
If given, this is the raw input without any IPython transformations
applied to it. If not given, ``source`` is used.
"""
if source_raw is None:
source_raw = source
Thomas Kluyver
Tweak to history_manager.store_inputs to pass tests.
r3419 source = source.rstrip('\n')
source_raw = source_raw.rstrip('\n')
Fernando Perez
Small fix and cleanup for exit/quit command filtering.
r3246
# do not store exit/quit commands
Thomas Kluyver
Replace exit command set with regex.
r3750 if self._exit_re.match(source_raw.strip()):
Satrajit Ghosh
removed quit/exit commands from history
r3243 return
Fernando Perez
Small fix and cleanup for exit/quit command filtering.
r3246
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 self.input_hist_parsed.append(source)
self.input_hist_raw.append(source_raw)
Thomas Kluyver
Tidy up store_inputs
r3390
Thomas Kluyver
Add locks for input and output caches.
r3713 with self.db_input_cache_lock:
self.db_input_cache.append((line_num, source, source_raw))
# Trigger to flush cache and write to DB.
if len(self.db_input_cache) >= self.db_cache_size:
self.save_flag.set()
Fernando Perez
Add support for accessing raw data to inputsplitter....
r3080
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087 # update the auto _i variables
self._iii = self._ii
self._ii = self._i
self._i = self._i00
self._i00 = source_raw
# hackish access to user namespace to create _i1,_i2... dynamically
Thomas Kluyver
Tidy up store_inputs
r3390 new_i = '_i%s' % line_num
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087 to_main = {'_i': self._i,
'_ii': self._ii,
'_iii': self._iii,
new_i : self._i00 }
self.shell.user_ns.update(to_main)
Thomas Kluyver
Ability to cache commits before writing to disk, to save power.
r3389
Thomas Kluyver
Allow history to store multiple outputs for a single input line.
r3415 def store_output(self, line_num):
Thomas Kluyver
Separate 'Out' in user_ns from the output history logging.
r3417 """If database output logging is enabled, this saves all the
outputs from the indicated prompt number to the database. It's
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 called by run_cell after code has been executed.
Parameters
----------
line_num : int
The line number from which to save outputs
"""
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391 return
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 output = self.output_hist_reprs[line_num]
Thomas Kluyver
Implement optional logging of output as suggested by Robert Kern.
r3391
Thomas Kluyver
Add locks for input and output caches.
r3713 with self.db_output_cache_lock:
self.db_output_cache.append((line_num, output))
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 if self.db_cache_size <= 1:
Thomas Kluyver
Put history saving into a separate thread.
r3711 self.save_flag.set()
def _writeout_input_cache(self, conn):
with conn:
Thomas Kluyver
Move with statement so history db cache is written out in one transaction (two if output history is being logged).
r3700 for line in self.db_input_cache:
Thomas Kluyver
Put history saving into a separate thread.
r3711 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 (self.session_number,)+line)
Thomas Kluyver
Put history saving into a separate thread.
r3711 def _writeout_output_cache(self, conn):
with conn:
Thomas Kluyver
Move with statement so history db cache is written out in one transaction (two if output history is being logged).
r3700 for line in self.db_output_cache:
Thomas Kluyver
Put history saving into a separate thread.
r3711 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 (self.session_number,)+line)
Thomas Kluyver
Put history saving into a separate thread.
r3711 def writeout_cache(self, conn=None):
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 """Write any entries in the cache to the database."""
Thomas Kluyver
Put history saving into a separate thread.
r3711 if conn is None:
conn = self.db
Thomas Kluyver
Add locks for input and output caches.
r3713
with self.db_input_cache_lock:
try:
Thomas Kluyver
Put history saving into a separate thread.
r3711 self._writeout_input_cache(conn)
Thomas Kluyver
Add error handling so SQLite history can recover from corrupt databases and session/line number collisions.
r3437 except sqlite3.IntegrityError:
Thomas Kluyver
new_session can be called from either thread.
r3714 self.new_session(conn)
Thomas Kluyver
Add locks for input and output caches.
r3713 print("ERROR! Session/line number was not unique in",
"database. History logging moved to new session",
self.session_number)
try: # Try writing to the new session. If this fails, don't recurse
self._writeout_input_cache(conn)
except sqlite3.IntegrityError:
pass
finally:
self.db_input_cache = []
with self.db_output_cache_lock:
try:
self._writeout_output_cache(conn)
except sqlite3.IntegrityError:
print("!! Session/line number for output was not unique",
"in database. Output will not be stored.")
finally:
self.db_output_cache = []
Fernando Perez
Finish removing spurious calls to logger and runlines....
r3087
Thomas Kluyver
Put history saving into a separate thread.
r3711
class HistorySavingThread(threading.Thread):
Thomas Kluyver
Add docstrings, improve history thread stop method.
r3716 """This thread takes care of writing history to the database, so that
the UI isn't held up while that happens.
It waits for the HistoryManager's save_flag to be set, then writes out
the history cache. The main thread is responsible for setting the flag when
the cache size reaches a defined threshold."""
Thomas Kluyver
Put history saving into a separate thread.
r3711 daemon = True
stop_now = False
def __init__(self, history_manager):
super(HistorySavingThread, self).__init__()
self.history_manager = history_manager
atexit.register(self.stop)
def run(self):
# We need a separate db connection per thread:
Thomas Kluyver
Catch errors in history save thread, and print a briefer error message, rather than an ugly traceback.
r3720 try:
self.db = sqlite3.connect(self.history_manager.hist_file)
while True:
self.history_manager.save_flag.wait()
if self.stop_now:
return
self.history_manager.save_flag.clear()
self.history_manager.writeout_cache(self.db)
except Exception as e:
print(("The history saving thread hit an unexpected error (%s)."
"History will not be written to the database.") % repr(e))
Thomas Kluyver
Put history saving into a separate thread.
r3711
def stop(self):
Thomas Kluyver
Add docstrings, improve history thread stop method.
r3716 """This can be called from the main thread to safely stop this thread.
Note that it does not attempt to write out remaining history before
exiting. That should be done by calling the HistoryManager's
end_session method."""
Thomas Kluyver
Put history saving into a separate thread.
r3711 self.stop_now = True
self.history_manager.save_flag.set()
Thomas Kluyver
Add docstrings, improve history thread stop method.
r3716 self.join()
Thomas Kluyver
Put history saving into a separate thread.
r3711
Thomas Kluyver
Passing IPython.core tests.
r3396
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 # To match, e.g. ~5/8-~2/3
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 range_re = re.compile(r"""
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 ((?P<startsess>~?\d+)/)?
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 (?P<start>\d+) # Only the start line num is compulsory
((?P<sep>[\-:])
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 ((?P<endsess>~?\d+)/)?
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 (?P<end>\d+))?
Thomas Kluyver
Refactor code-finding logic, and use it for %save and %macro as well.
r3493 $""", re.VERBOSE)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394
def extract_hist_ranges(ranges_str):
"""Turn a string of history ranges into 3-tuples of (session, start, stop).
Examples
--------
Thomas Kluyver
Fix up extracting ranges from previous sessions, now using ~2/8 syntax instead of ~2#8
r3395 list(extract_input_ranges("~8/5-~7/4 2"))
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
"""
for range_str in ranges_str.split():
rmatch = range_re.match(range_str)
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 if not rmatch:
continue
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 start = int(rmatch.group("start"))
end = rmatch.group("end")
end = int(end) if end else start+1 # If no end specified, get (a, a+1)
if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
end += 1
startsess = rmatch.group("startsess") or "0"
endsess = rmatch.group("endsess") or startsess
startsess = int(startsess.replace("~","-"))
endsess = int(endsess.replace("~","-"))
assert endsess >= startsess
if endsess == startsess:
yield (startsess, start, end)
continue
# Multiple sessions in one range:
yield (startsess, start, None)
for sess in range(startsess+1, endsess):
yield (sess, 1, None)
yield (endsess, 1, end)
def _format_lineno(session, line):
"""Helper function to format line numbers properly."""
if session == 0:
return str(line)
return "%s#%s" % (session, line)
vivainio
crlf normalization
r851
Thomas Kluyver
Move skip_doctest decorator to separate module, so that it can be used without triggering other imports.
r3886 @skip_doctest
vivainio
crlf normalization
r851 def magic_history(self, parameter_s = ''):
"""Print input history (_i<n> variables), with most recent last.
%history -> print at most 40 inputs (some may be multi-line)\\
%history n -> print at most n inputs\\
%history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 By default, input history is printed without line numbers so it can be
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 directly pasted into an editor. Use -n to show them.
Ranges of history can be indicated using the syntax:
4 : Line 4, current session
4-6 : Lines 4-6, current session
243/1-5: Lines 1-5, session 243
~2/7 : Line 7, session 2 before current
~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
of 6 sessions ago.
Multiple ranges can be entered, separated by spaces
The same syntax is used by %macro, %save, %edit, %rerun
vivainio
crlf normalization
r851
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 Options:
vivainio
crlf normalization
r851
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 -n: print line numbers for each input.
vivainio
crlf normalization
r851 This feature is only available if numbered prompts are in use.
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 -o: also print outputs for each input.
-p: print classic '>>>' python prompts before each input. This is useful
for making documentation, and in conjunction with -o, for producing
doctest-ready output.
Fernando Perez
Change %history to default to 'raw' history.
r2899 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
vivainio
crlf normalization
r851
Fernando Perez
Change %history to default to 'raw' history.
r2899 -t: print the 'translated' history, as IPython understands it. IPython
filters your input and converts it all into valid Python source before
executing it (things like magics or aliases are turned into function
calls, for example). With this option, you'll see the native history
instead of the user-entered version: '%cd /' will be seen as
'get_ipython().magic("%cd /")' instead of '%cd /'.
vivainio
crlf normalization
r851
-g: treat the arg as a pattern to grep for in (full) history.
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 This includes the saved history (almost all commands ever written).
Use '%hist -g' to show full saved history (may be very long).
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394
-l: get the last n lines from all sessions. Specify n as a single arg, or
the default is the last 10 lines.
fperez
Forgot to commit docstring about this feature
r961
-f FILENAME: instead of printing the output to the screen, redirect it to
the given file. The file is always overwritten, though IPython asks for
confirmation first if it already exists.
Vishnu S G
Wrote example for %history...
r3326
Thomas Kluyver
Tweaks to RST formatting.
r3337 Examples
--------
Vishnu S G
Wrote example for %history...
r3326 ::
In [6]: %hist -n 4 6
4:a = 12
5:print a**2
vivainio
crlf normalization
r851 """
Fernando Perez
Fix off-by-one bug in history because we weren't correctly updating it....
r2993 if not self.shell.displayhook.do_full_cache:
Fernando Perez
Created HistoryManager to better organize history control....
r3079 print('This feature is only available if numbered prompts are in use.')
vivainio
crlf normalization
r851 return
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380
# For brevity
history_manager = self.shell.history_manager
Thomas Kluyver
Fix various small bugs.
r3398
def _format_lineno(session, line):
"""Helper function to format line numbers properly."""
if session in (0, history_manager.session_number):
return str(line)
return "%s/%s" % (session, line)
fperez
Add -f flag to %history to direct output to file
r960
# Check if output to specific file was requested.
try:
outfname = opts['f']
except KeyError:
MinRK
io.Term.cin/out/err replaced by io.stdin/out/err...
r3800 outfile = io.stdout # default
fperez
Add -f flag to %history to direct output to file
r960 # We don't want to close stdout at the end!
close_at_end = False
else:
if os.path.exists(outfname):
MinRK
io.Term.cin/out/err replaced by io.stdin/out/err...
r3800 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
Fernando Perez
Created HistoryManager to better organize history control....
r3079 print('Aborting.')
fperez
Add -f flag to %history to direct output to file
r960 return
vivainio
crlf normalization
r851
Fernando Perez
Fix a number of bugs with %history, add proper tests....
r1762 outfile = open(outfname,'w')
close_at_end = True
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380
print_nums = 'n' in opts
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 get_output = 'o' in opts
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380 pyprompts = 'p' in opts
# Raw history is the default
raw = not('t' in opts)
Fernando Perez
Fix a number of bugs with %history, add proper tests....
r1762
vivainio
crlf normalization
r851 default_length = 40
pattern = None
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394
Thomas Kluyver
Simplify magic_history display code, allow get_hist_search to include output in return values, and add some unit tests.
r3400 if 'g' in opts: # Glob search
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 pattern = "*" + args + "*" if args else "*"
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = history_manager.search(pattern, raw=raw, output=get_output)
Thomas Kluyver
%history -g should show line numbers automatically.
r4371 print_nums = True
Thomas Kluyver
Simplify magic_history display code, allow get_hist_search to include output in return values, and add some unit tests.
r3400 elif 'l' in opts: # Get 'tail'
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 try:
n = int(args)
except ValueError, IndexError:
n = 10
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = history_manager.get_tail(n, raw=raw, output=get_output)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 else:
if args: # Get history by ranges
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = history_manager.get_range_by_str(args, raw, get_output)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 else: # Just get history for the current session
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = history_manager.get_range(raw=raw, output=get_output)
vivainio
crlf normalization
r851
Thomas Kluyver
Simplify magic_history display code, allow get_hist_search to include output in return values, and add some unit tests.
r3400 # We could be displaying the entire history, so let's not try to pull it
# into a list in memory. Anything that needs more space will just misalign.
width = 4
vivainio
crlf normalization
r851
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 for session, lineno, inline in hist:
Fernando Perez
Expand tabs to 4 spaces in %history.
r2970 # Print user history with tabs expanded to 4 spaces. The GUI clients
# use hard tabs for easier usability in auto-indented code, but we want
# to produce PEP-8 compliant history for safe pasting into an editor.
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 if get_output:
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380 inline, output = inline
inline = inline.expandtabs(4).rstrip()
vivainio
crlf normalization
r851
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380 multiline = "\n" in inline
Thomas Kluyver
Simplify magic_history display code, allow get_hist_search to include output in return values, and add some unit tests.
r3400 line_sep = '\n' if multiline else ' '
vivainio
crlf normalization
r851 if print_nums:
Thomas Kluyver
Fix various small bugs.
r3398 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
Thomas Kluyver
Passing IPython.core tests.
r3396 line_sep), file=outfile, end='')
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 if pyprompts:
Thomas Kluyver
Simplifying code in several places.
r3381 print(">>> ", end="", file=outfile)
Fernando Perez
Changed %hist to default to NOT printing numbers, added -p and -o options....
r2441 if multiline:
Thomas Kluyver
Simplifying code in several places.
r3381 inline = "\n... ".join(inline.splitlines()) + "\n..."
print(inline, file=outfile)
Thomas Kluyver
Tidy up history retrieval APIs, and magic commands using them (%hist, %macro, %save, %edit)
r3394 if get_output and output:
Thomas Kluyver
History expects single output per cell, and doesn't use JSON to store them in the database.
r3741 print(output, file=outfile)
fperez
Add -f flag to %history to direct output to file
r960
if close_at_end:
outfile.close()
vivainio
crlf normalization
r851
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 def magic_rep(self, arg):
Thomas Kluyver
Prefer %recall over %rep in docstring.
r4443 r"""Repeat a command, or get command to input line for editing. %recall and
%rep are equivalent.
vivainio
crlf normalization
r851
Thomas Kluyver
Prefer %recall over %rep in docstring.
r4443 - %recall (no arguments):
vivainio
crlf normalization
r851
Place a string version of last computation result (stored in the special '_'
variable) to the next input prompt. Allows you to create elaborate command
lines without using copy-paste::
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 In[1]: l = ["hei", "vaan"]
In[2]: "".join(l)
Out[2]: heivaan
In[3]: %rep
In[4]: heivaan_ <== cursor blinking
vivainio
crlf normalization
r851
Thomas Kluyver
Prefer %recall over %rep in docstring.
r4443 %recall 45
vivainio
crlf normalization
r851
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 Place history line 45 on the next input prompt. Use %hist to find
out the number.
vivainio
crlf normalization
r851
Thomas Kluyver
Prefer %recall over %rep in docstring.
r4443 %recall 1-4
vivainio
crlf normalization
r851
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 Combine the specified lines into one cell, and place it on the next
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 input prompt. See %history for the slice syntax.
vivainio
crlf normalization
r851
Thomas Kluyver
Prefer %recall over %rep in docstring.
r4443 %recall foo+bar
vivainio
crlf normalization
r851
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 If foo+bar can be evaluated in the user namespace, the result is
placed at the next input prompt. Otherwise, the history is searched
for lines which contain that substring, and the most recent one is
placed at the next input prompt.
vivainio
crlf normalization
r851 """
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 if not arg: # Last output
Fernando Perez
Fix off-by-one bug in history because we weren't correctly updating it....
r2993 self.set_next_input(str(self.shell.user_ns["_"]))
vivainio
crlf normalization
r851 return
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 # Get history range
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 histlines = self.history_manager.get_range_by_str(arg)
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 cmd = "\n".join(x[2] for x in histlines)
if cmd:
self.set_next_input(cmd.rstrip())
return
vivainio
crlf normalization
r851
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 try: # Variable in user namespace
cmd = str(eval(arg, self.shell.user_ns))
except Exception: # Search for term in history
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 histlines = self.history_manager.search("*"+arg+"*")
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 for h in reversed([x[2] for x in histlines]):
vivainio
crlf normalization
r851 if 'rep' in h:
continue
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 self.set_next_input(h.rstrip())
return
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 else:
self.set_next_input(cmd.rstrip())
print("Couldn't evaluate or find in history:", arg)
def magic_rerun(self, parameter_s=''):
"""Re-run previous input
By default, you can specify ranges of input history to be repeated
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 (as with %history). With no arguments, it will repeat the last line.
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418
Options:
-l <n> : Repeat the last n lines of input, not including the
current command.
-g foo : Repeat the most recent line which contains foo
"""
opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
if "l" in opts: # Last n lines
Thomas Kluyver
Further refinements to history interfaces.
r3420 n = int(opts['l'])
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = self.history_manager.get_tail(n)
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 elif "g" in opts: # Search
p = "*"+opts['g']+"*"
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = list(self.history_manager.search(p))
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 for l in reversed(hist):
if "rerun" not in l[2]:
hist = [l] # The last match which isn't a %rerun
break
else:
hist = [] # No matches except %rerun
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 elif args: # Specify history ranges
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = self.history_manager.get_range_by_str(args)
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 else: # Last line
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 hist = self.history_manager.get_tail(1)
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 hist = [x[2] for x in hist]
if not hist:
print("No lines in history match specification")
return
histlines = "\n".join(hist)
print("=== Executing: ===")
print(histlines)
print("=== Output: ===")
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 self.run_cell("\n".join(hist), store_history=False)
vivainio
crlf normalization
r851
def init_ipython(ip):
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 ip.define_magic("rep", magic_rep)
Thomas Kluyver
Separating %rep and %rerun magic commands. Trouble with tests.
r3418 ip.define_magic("recall", magic_rep)
ip.define_magic("rerun", magic_rerun)
Thomas Kluyver
Initial fix for magic %rep function (was broken by new history system). Needs a bit of further thought.
r3416 ip.define_magic("hist",magic_history) # Alternative name
Brian Granger
Continuing a massive refactor of everything.
r2205 ip.define_magic("history",magic_history)
vivainio
crlf normalization
r851
Fernando Perez
Fix %history magics....
r2421 # XXX - ipy_completers are in quarantine, need to be updated to new apis
#import ipy_completers
Fernando Perez
Progress towards getting the test suite in shape again....
r2392 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')