Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

HistoryManager.get_session_info() #679

Merged
merged 3 commits into from

3 participants

Min RK Thomas Kluyver Fernando Perez
Min RK
Owner

add simple get_session_info method to HistoryManager for fetching session timestamps, etc.

Also sets detect_types flags on the db connection, so timestamps are retrieved as datetime objects.

The test history file has been moved to a tempdir, so that we don't get test_hist.sqlite files all over the filesystem when running the test suite.

minrk added some commits
Min RK minrk put test_hist.sqlite in tempdir, to prevent polluting filesystem 0279eb0
Min RK minrk add get_session_info to HistoryManager for querying session table
Also set detect_types flags on the connection, so timestamps are
retrieved as datetime objects.

Associated type checking test included.
30c9fcb
Thomas Kluyver
Owner

This seems sensible. I'm planning, when I have time, to pull out the methods for reading history into a HistoryAccessor class which can be instantiated without an InteractiveShell, so it can be used by tools for browsing or dumping history. HistoryManager will then subclass that, and add the methods for storing history from the shell.

IPython/testing/tools.py
@@ -170,7 +171,7 @@ def default_config():
config.TerminalInteractiveShell.colors = 'NoColor'
config.TerminalTerminalInteractiveShell.term_title = False,
config.TerminalInteractiveShell.autocall = 0
- config.HistoryManager.hist_file = u'test_hist.sqlite'
+ config.HistoryManager.hist_file = os.path.join(tempfile.mkdtemp(), u'test_hist.sqlite')
Fernando Perez Owner
fperez added a note

This file should be added to the list of files we delete on exit, so that we clean up after ourselves. But instead of making a temp directory, let's simply make a temp file with the suffix 'test_hist.sqlite'. Then the cleanup is simply a matter of removing the file on exit, which can be done by registering it with the ipython instance's .tempfiles attribute, that all get deleted at interpeter shutdown time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Min RK minrk add test history db to shell.tempfiles for cleanup
* end_history_session moved before tempfile cleanup in shell.atexit_operations,
  to prevent access to file after deletion
503aeea
Fernando Perez fperez merged commit 9dfe802 into from
Fernando Perez fperez referenced this pull request from a commit
Commit has since been removed from the repository and is no longer available.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Aug 4, 2011
  1. Min RK
  2. Min RK

    add get_session_info to HistoryManager for querying session table

    minrk authored
    Also set detect_types flags on the connection, so timestamps are
    retrieved as datetime objects.
    
    Associated type checking test included.
Commits on Aug 17, 2011
  1. Min RK

    add test history db to shell.tempfiles for cleanup

    minrk authored
    * end_history_session moved before tempfile cleanup in shell.atexit_operations,
      to prevent access to file after deletion
This page is out of date. Refresh to see the latest.
30 IPython/core/history.py
View
@@ -129,7 +129,8 @@ def __init__(self, shell, config=None, **traits):
def init_db(self):
"""Connect to the database, and create tables if necessary."""
- self.db = sqlite3.connect(self.hist_file)
+ # use detect_types so that timestamps return datetime objects
+ self.db = sqlite3.connect(self.hist_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
primary key autoincrement, start timestamp,
end timestamp, num_cmds integer, remark text)""")
@@ -213,6 +214,33 @@ def _run_sql(self, sql, params, raw=True, output=False):
return cur
+ 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()
+
+
def get_tail(self, n=10, raw=True, output=False, include_latest=False):
"""Get the last n lines from the history database.
8 IPython/core/interactiveshell.py
View
@@ -2540,6 +2540,11 @@ def atexit_operations(self):
code that has the appropriate information, rather than trying to
clutter
"""
+ # Close the history session (this stores the end time and line count)
+ # this must be *before* the tempfile cleanup, in case of temporary
+ # history db
+ self.history_manager.end_session()
+
# Cleanup all tempfiles left around
for tfile in self.tempfiles:
try:
@@ -2547,9 +2552,6 @@ def atexit_operations(self):
except OSError:
pass
- # Close the history session (this stores the end time and line count)
- self.history_manager.end_session()
-
# Clear all user namespaces to release all references cleanly.
self.reset(new_session=False)
7 IPython/core/tests/test_history.py
View
@@ -9,7 +9,7 @@
import os
import sys
import unittest
-
+from datetime import datetime
# third party
import nose.tools as nt
@@ -107,3 +107,8 @@ def test_magic_rerun():
nt.assert_equal(ip.user_ns["a"], 11)
ip.run_cell("%rerun")
nt.assert_equal(ip.user_ns["a"], 12)
+
+def test_timestamp_type():
+ ip = get_ipython()
+ info = ip.history_manager.get_session_info()
+ nt.assert_true(isinstance(info[1], datetime))
3  IPython/testing/globalipapp.py
View
@@ -194,6 +194,9 @@ def start_ipython():
# A few more tweaks needed for playing nicely with doctests...
+ # remove history file
+ shell.tempfiles.append(config.HistoryManager.hist_file)
+
# These traps are normally only active for interactive use, set them
# permanently since we'll be mocking interactive sessions.
shell.builtin_trap.activate()
3  IPython/testing/tools.py
View
@@ -31,6 +31,7 @@
import os
import re
import sys
+import tempfile
from contextlib import contextmanager
@@ -170,7 +171,7 @@ def default_config():
config.TerminalInteractiveShell.colors = 'NoColor'
config.TerminalTerminalInteractiveShell.term_title = False,
config.TerminalInteractiveShell.autocall = 0
- config.HistoryManager.hist_file = u'test_hist.sqlite'
+ config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite')
config.HistoryManager.db_cache_size = 10000
return config
Something went wrong with that request. Please try again.