| 1 |
#!/usr/bin/env python |
| 2 |
"""Extract a session from the IPython input history. |
| 3 |
|
| 4 |
Usage: |
| 5 |
ipython-get-history.py sessionnumber [outputfile] |
| 6 |
|
| 7 |
If outputfile is not given, the relevant history is written to stdout. If |
| 8 |
outputfile has a .py extension, the translated history (without IPython's |
| 9 |
special syntax) will be extracted. |
| 10 |
|
| 11 |
Example: |
| 12 |
./ipython-get-history.py 57 record.ipy |
| 13 |
|
| 14 |
|
| 15 |
This script is a simple demonstration of HistoryAccessor. It should be possible |
| 16 |
to build much more flexible and powerful tools to browse and pull from the |
| 17 |
history database. |
| 18 |
""" |
| 19 |
|
| 20 |
import sys |
| 21 |
from pathlib import Path |
| 22 |
|
| 23 |
from IPython.core.history import HistoryAccessor |
| 24 |
|
| 25 |
session_number = int(sys.argv[1]) |
| 26 |
if len(sys.argv) > 2: |
| 27 |
filepath = Path(sys.argv[2]) |
| 28 |
dest = open(filepath, "w", encoding="utf-8") |
| 29 |
raw = not filepath.name.endswith(".py") |
| 30 |
else: |
| 31 |
dest = sys.stdout |
| 32 |
raw = True |
| 33 |
|
| 34 |
with dest: |
| 35 |
dest.write("# coding: utf-8\n") |
| 36 |
|
| 37 |
# Profiles other than 'default' can be specified here with a profile= argument: |
| 38 |
hist = HistoryAccessor() |
| 39 |
|
| 40 |
for session, lineno, cell in hist.get_range(session=session_number, raw=raw): |
| 41 |
dest.write(cell + "\n") |