execnb 0.2.4__tar.gz → 0.2.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -0,0 +1 @@
1
+ __version__ = "0.2.6"
@@ -12,6 +12,7 @@ d = { 'settings': { 'branch': 'main',
12
12
  'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
13
13
  'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
14
14
  'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
15
+ 'execnb.shell.CaptureShell.load_profile': ('shell.html#captureshell.load_profile', 'execnb/shell.py'),
15
16
  'execnb.shell.CaptureShell.nbopen': ('shell.html#captureshell.nbopen', 'execnb/shell.py'),
16
17
  'execnb.shell.CaptureShell.nbrun': ('shell.html#captureshell.nbrun', 'execnb/shell.py'),
17
18
  'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
@@ -41,6 +42,7 @@ d = { 'settings': { 'branch': 'main',
41
42
  'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
42
43
  'execnb.shell._out_stream': ('shell.html#_out_stream', 'execnb/shell.py'),
43
44
  'execnb.shell._pre': ('shell.html#_pre', 'execnb/shell.py'),
45
+ 'execnb.shell._profile_cfg': ('shell.html#_profile_cfg', 'execnb/shell.py'),
44
46
  'execnb.shell._strip': ('shell.html#_strip', 'execnb/shell.py'),
45
47
  'execnb.shell.exec_nb': ('shell.html#exec_nb', 'execnb/shell.py'),
46
48
  'execnb.shell.find_output': ('shell.html#find_output', 'execnb/shell.py'),
@@ -18,6 +18,9 @@ try:
18
18
  if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
19
19
  except RuntimeError: pass # if re-running cell
20
20
 
21
+ from traitlets.config import Config
22
+ from traitlets.config.loader import PyFileConfigLoader
23
+ from IPython.paths import get_ipython_dir
21
24
  from IPython.core.interactiveshell import InteractiveShell, ExecutionInfo, ExecutionResult
22
25
  from IPython.core.displayhook import DisplayHook
23
26
  from IPython.utils.capture import capture_output
@@ -32,7 +35,6 @@ from html import escape
32
35
  from fastcore.nbio import *
33
36
  from fastcore.nbio import _dict2obj
34
37
 
35
-
36
38
  # %% ../nbs/00_shell.ipynb #6913382c
37
39
  class _CustDisplayHook(DisplayHook):
38
40
  def write_output_prompt(self): pass
@@ -45,12 +47,27 @@ def __repr__(self: ExecutionInfo): return f'cell: {self.raw_cell}; id: {self.cel
45
47
  @patch
46
48
  def __repr__(self: ExecutionResult): return f'result: {self.result}; err: {self.error_in_exec}; info: <{self.info}>'
47
49
 
50
+ # %% ../nbs/00_shell.ipynb #9c879b74
51
+ def _profile_cfg(name='default'):
52
+ "Merged config, extensions, and profile dir for IPython profile `name`"
53
+ pd = Path(get_ipython_dir())/f'profile_{name}'
54
+ cfg,exts = Config(),[]
55
+ for f in ('ipython_config.py','ipython_kernel_config.py'):
56
+ if not (pd/f).exists(): continue
57
+ c = PyFileConfigLoader(f, path=str(pd)).load_config()
58
+ e = c.get('InteractiveShellApp', {}).get('extensions', [])
59
+ exts += e.get_value([]) if hasattr(e, 'get_value') else e
60
+ cfg.merge(c)
61
+ return cfg,exts,pd
62
+
48
63
  # %% ../nbs/00_shell.ipynb #e3fb2bee
49
64
  class CaptureShell(InteractiveShell):
50
65
  displayhook_class = _CustDisplayHook
51
66
 
52
- def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None):
53
- super().__init__()
67
+ def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None, profile:bool=False):
68
+ cfg = _profile_cfg()[0] if profile else Config()
69
+ if not history: cfg.HistoryManager.hist_file = ':memory:'
70
+ super().__init__(config=cfg)
54
71
  self.history_manager.enabled = history
55
72
  self.timeout = timeout
56
73
  self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
@@ -64,6 +81,7 @@ class CaptureShell(InteractiveShell):
64
81
  self.enable_matplotlib("inline")
65
82
  self._run("from matplotlib_inline.backend_inline import set_matplotlib_formats")
66
83
  self._run(f"set_matplotlib_formats('{mpl_format}')")
84
+ if profile: self.load_profile()
67
85
 
68
86
  def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
69
87
  stdout=True, stderr=True, display=True, verbose=False):
@@ -96,6 +114,24 @@ def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, she
96
114
  finally:
97
115
  if timeout: signal.alarm(0)
98
116
 
117
+ # %% ../nbs/00_shell.ipynb #a05e1b43
118
+ @patch
119
+ def load_profile(self:CaptureShell, name='default'):
120
+ "Load profile `name`'s extensions and run its startup files (output suppressed), as `ipykernel` does"
121
+ cfg,exts,pd = _profile_cfg(name)
122
+ warns = []
123
+ with capture_output():
124
+ for o in exts:
125
+ try: self.extension_manager.load_extension(o)
126
+ except Exception as e: warns.append(f"Failed loading extension {o}: {e}")
127
+ sd = pd/'startup'
128
+ for f in sorted([*sd.glob('*.py'), *sd.glob('*.ipy')]) if sd.is_dir() else []:
129
+ try:
130
+ if f.suffix=='.ipy': self.safe_execfile_ipy(f, raise_exceptions=True)
131
+ else: self.safe_execfile(f, self.user_ns, raise_exceptions=True)
132
+ except Exception as e: warns.append(f"Failed running startup file {f}: {e}")
133
+ for w in warns: warnings.warn(w)
134
+
99
135
  # %% ../nbs/00_shell.ipynb #a1eb7703
100
136
  def format_exc(e):
101
137
  "Format exception `e` as a string list"
@@ -292,19 +328,21 @@ def _is_noeval(src):
292
328
 
293
329
  def select_cells(
294
330
  nb, # A notebook read with `read_nb`
295
- msgid:str=None, # Cell id prefix to match
331
+ msgid:str=None, # Cell id, or unique prefix, to match
296
332
  above:bool=False, # Include the matched cell and all cells above it?
297
333
  below:bool=False, # Include the matched cell and all cells below it?
298
334
  all:bool=False, # Include all code cells (ignores `msgid`)?
299
335
  exported:bool=False, # Only cells with `#| export` or `#| exports`?
300
336
  skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
301
337
  ):
302
- "Select code cells from `nb` by cell id prefix"
338
+ "Select code cells from `nb` by cell id or unique prefix"
303
339
  cells = [o for o in nb.cells if o.cell_type=='code']
304
340
  if not all:
305
341
  if not msgid: raise ValueError('`msgid` required unless `all=True`')
306
- idx = first(i for i,o in enumerate(cells) if str(o.id).startswith(msgid))
307
- if idx is None: raise ValueError(f'No code cell id starting with {msgid!r}')
342
+ idxs = [i for i,o in enumerate(cells) if str(o.id).startswith(msgid)]
343
+ if not idxs: raise ValueError(f'No code cell id starting with {msgid!r}')
344
+ if len(idxs)>1: raise ValueError(f'Multiple code cell ids start with {msgid!r}: {", ".join(str(cells[i].id) for i in idxs)}')
345
+ idx = idxs[0]
308
346
  if above: cells = cells[:idx+1]
309
347
  elif below: cells = cells[idx:]
310
348
  else: cells = [cells[idx]]
@@ -319,12 +357,14 @@ from fastcore.nbio import render_text
319
357
  @patch
320
358
  def nbopen(self:CaptureShell, fname:str|Path):
321
359
  "Set the default notebook for `nbrun`"
322
- self._nbrun_fname = Path(fname)
360
+ fname = Path(fname)
361
+ if not fname.exists(): raise FileNotFoundError(fname)
362
+ self._nbrun_fname = fname
323
363
 
324
364
  @patch
325
365
  def nbrun(
326
366
  self:CaptureShell,
327
- msgid:str=None, # Cell id prefix to run
367
+ *msgids:str, # Cell id prefixes to run, in the order given
328
368
  fname:str|Path=None, # Notebook path (defaults to last `nbopen`)
329
369
  above:bool=False, # Also run all cells above the match?
330
370
  below:bool=False, # Also run all cells below the match?
@@ -337,9 +377,11 @@ def nbrun(
337
377
  if not fname: raise ValueError('No `fname` passed and no notebook opened with `nbopen`')
338
378
  self.nbopen(fname)
339
379
  nb = read_nb(fname)
340
- for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
341
- res = render_text(self.run(cell.source))
342
- if res: print(f'--- {cell.id} ---\n{res}')
380
+ if all or not msgids: msgids = (None,)
381
+ for msgid in msgids:
382
+ for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
383
+ res = render_text(self.run(cell.source))
384
+ if res: print(f'--- {cell.id} ---\n{res}')
343
385
 
344
386
  # %% ../nbs/00_shell.ipynb #1227c8b1
345
387
  @call_parse
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -1 +0,0 @@
1
- __version__ = "0.2.4"
File without changes
File without changes
File without changes
File without changes
File without changes