execnb 0.2.9__tar.gz → 0.2.10__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.9
3
+ Version: 0.2.10
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -15,7 +15,7 @@ Classifier: Programming Language :: Python :: 3 :: Only
15
15
  Requires-Python: >=3.7
16
16
  Description-Content-Type: text/markdown
17
17
  License-File: LICENSE
18
- Requires-Dist: fastcore>=2.1.2
18
+ Requires-Dist: fastcore>=2.1.17
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -0,0 +1 @@
1
+ __version__ = "0.2.10"
@@ -7,20 +7,25 @@ d = { 'settings': { 'branch': 'main',
7
7
  'lib_path': 'execnb'},
8
8
  'syms': { 'execnb.shell': { 'execnb.shell.CaptureShell': ('shell.html#captureshell', 'execnb/shell.py'),
9
9
  'execnb.shell.CaptureShell.__init__': ('shell.html#captureshell.__init__', 'execnb/shell.py'),
10
+ 'execnb.shell.CaptureShell._captured': ('shell.html#captureshell._captured', 'execnb/shell.py'),
10
11
  'execnb.shell.CaptureShell._run': ('shell.html#captureshell._run', 'execnb/shell.py'),
12
+ 'execnb.shell.CaptureShell._run_async': ('shell.html#captureshell._run_async', 'execnb/shell.py'),
13
+ 'execnb.shell.CaptureShell._run_res': ('shell.html#captureshell._run_res', 'execnb/shell.py'),
14
+ 'execnb.shell.CaptureShell.arun_cell': ('shell.html#captureshell.arun_cell', 'execnb/shell.py'),
11
15
  'execnb.shell.CaptureShell.cell': ('shell.html#captureshell.cell', 'execnb/shell.py'),
12
16
  'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
13
17
  'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
14
18
  'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
15
19
  'execnb.shell.CaptureShell.load_profile': ('shell.html#captureshell.load_profile', 'execnb/shell.py'),
16
- 'execnb.shell.CaptureShell.nbopen': ('shell.html#captureshell.nbopen', 'execnb/shell.py'),
17
- 'execnb.shell.CaptureShell.nbrun': ('shell.html#captureshell.nbrun', 'execnb/shell.py'),
18
20
  'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
19
21
  'execnb.shell.CaptureShell.run': ('shell.html#captureshell.run', 'execnb/shell.py'),
20
22
  'execnb.shell.CaptureShell.run_all': ('shell.html#captureshell.run_all', 'execnb/shell.py'),
21
23
  'execnb.shell.CaptureShell.run_async': ('shell.html#captureshell.run_async', 'execnb/shell.py'),
22
24
  'execnb.shell.CaptureShell.run_cell': ('shell.html#captureshell.run_cell', 'execnb/shell.py'),
25
+ 'execnb.shell.CaptureShell.run_text': ('shell.html#captureshell.run_text', 'execnb/shell.py'),
23
26
  'execnb.shell.CaptureShell.set_path': ('shell.html#captureshell.set_path', 'execnb/shell.py'),
27
+ 'execnb.shell.CaptureShell.showsyntaxerror': ('shell.html#captureshell.showsyntaxerror', 'execnb/shell.py'),
28
+ 'execnb.shell.CaptureShell.showtraceback': ('shell.html#captureshell.showtraceback', 'execnb/shell.py'),
24
29
  'execnb.shell.ExecutionInfo.__repr__': ('shell.html#executioninfo.__repr__', 'execnb/shell.py'),
25
30
  'execnb.shell.ExecutionResult.__repr__': ('shell.html#executionresult.__repr__', 'execnb/shell.py'),
26
31
  'execnb.shell.NbResult': ('shell.html#nbresult', 'execnb/shell.py'),
@@ -35,8 +40,6 @@ d = { 'settings': { 'branch': 'main',
35
40
  'execnb/shell.py'),
36
41
  'execnb.shell._false': ('shell.html#_false', 'execnb/shell.py'),
37
42
  'execnb.shell._format_mimedata': ('shell.html#_format_mimedata', 'execnb/shell.py'),
38
- 'execnb.shell._is_exported': ('shell.html#_is_exported', 'execnb/shell.py'),
39
- 'execnb.shell._is_noeval': ('shell.html#_is_noeval', 'execnb/shell.py'),
40
43
  'execnb.shell._mk_out': ('shell.html#_mk_out', 'execnb/shell.py'),
41
44
  'execnb.shell._out_exc': ('shell.html#_out_exc', 'execnb/shell.py'),
42
45
  'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
@@ -51,5 +54,4 @@ d = { 'settings': { 'branch': 'main',
51
54
  'execnb.shell.out_error': ('shell.html#out_error', 'execnb/shell.py'),
52
55
  'execnb.shell.out_exec': ('shell.html#out_exec', 'execnb/shell.py'),
53
56
  'execnb.shell.out_stream': ('shell.html#out_stream', 'execnb/shell.py'),
54
- 'execnb.shell.render_outputs': ('shell.html#render_outputs', 'execnb/shell.py'),
55
- 'execnb.shell.select_cells': ('shell.html#select_cells', 'execnb/shell.py')}}}
57
+ 'execnb.shell.render_outputs': ('shell.html#render_outputs', 'execnb/shell.py')}}}
@@ -6,14 +6,16 @@ Docs: https://AnswerDotAI.github.io/execnb/shell.html.md"""
6
6
 
7
7
  # %% auto #0
8
8
  __all__ = ['leading_comment_lines', 'CaptureShell', 'format_exc', 'NbResult', 'render_outputs', 'find_output', 'out_exec',
9
- 'out_stream', 'out_error', 'select_cells', 'exec_nb', 'SmartCompleter']
9
+ 'out_stream', 'out_error', 'exec_nb', 'SmartCompleter']
10
10
 
11
11
  # %% ../nbs/00_shell.ipynb #535003cf
12
12
  from fastcore.utils import *
13
+ from fastcore.meta import delegates
13
14
  from fastcore.script import call_parse
14
15
  from fastcore.ansi import strip_ansi
15
16
 
16
17
  import multiprocessing,types,traceback,signal
18
+ from contextlib import contextmanager
17
19
  try:
18
20
  if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
19
21
  except RuntimeError: pass # if re-running cell
@@ -70,6 +72,7 @@ def leading_comment_lines(lines):
70
72
  # %% ../nbs/00_shell.ipynb #e3fb2bee
71
73
  class CaptureShell(InteractiveShell):
72
74
  displayhook_class = _CustDisplayHook
75
+ _nested = False
73
76
 
74
77
  def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None, profile:bool=False):
75
78
  cfg = _profile_cfg()[0] if profile else Config()
@@ -78,7 +81,7 @@ class CaptureShell(InteractiveShell):
78
81
  self.input_transformers_cleanup.append(leading_comment_lines)
79
82
  self.history_manager.enabled = history
80
83
  self.timeout = timeout
81
- self.result,self.exc,self._cell_idx,self._fname,self._nested = None,None,None,None,False
84
+ self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
82
85
  if path: self.set_path(path)
83
86
  self.display_formatter.active = True
84
87
  if not in_notebook(): InteractiveShell._instance = self
@@ -91,29 +94,6 @@ class CaptureShell(InteractiveShell):
91
94
  self._run(f"set_matplotlib_formats('{mpl_format}')")
92
95
  if profile: self.load_profile()
93
96
 
94
- def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
95
- stdout=True, stderr=True, display=True, timeout=None, verbose=False):
96
- "Captured execution: run `raw_cell` with output capture and optional timeout, returning an `AttrDict`"
97
- # TODO what if there's a comment?
98
- semic = raw_cell.rstrip().endswith(';') and not raw_cell.lstrip().startswith('%%')
99
- if not timeout: timeout = self.timeout
100
- if timeout:
101
- def handler(*args): raise TimeoutError()
102
- signal.signal(signal.SIGALRM, handler)
103
- signal.alarm(timeout)
104
- try:
105
- with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
106
- old,self._nested = self._nested,True
107
- try: result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
108
- finally: self._nested = old
109
- finally:
110
- if timeout: signal.alarm(0)
111
- e = result.error_in_exec or result.error_before_exec
112
- if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
113
- e.args = (f"{e} A cell magic (%%) must start the cell; remove or move the lines above it.",)
114
- return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr, display_objects=c.outputs,
115
- exception=e, quiet=semic)
116
-
117
97
  def set_path(self, path):
118
98
  "Add `path` to python path, or `path.parent` if it's a file"
119
99
  path = Path(path)
@@ -131,6 +111,78 @@ def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, she
131
111
  stdout=stdout, stderr=stderr, display=display, timeout=timeout, verbose=verbose)
132
112
 
133
113
 
114
+ # %% ../nbs/00_shell.ipynb #6f0cac34
115
+ @patch
116
+ @contextmanager
117
+ def _captured(self:CaptureShell, stdout=True, stderr=True, display=True, timeout=None, verbose=False):
118
+ "Output capture and optional SIGALRM timeout around one cell run"
119
+ if not timeout: timeout = self.timeout
120
+ if timeout:
121
+ def handler(*args): raise TimeoutError()
122
+ signal.signal(signal.SIGALRM, handler)
123
+ signal.alarm(timeout)
124
+ try:
125
+ with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
126
+ old,self._nested = self._nested,True
127
+ try: yield c
128
+ finally: self._nested = old
129
+ finally:
130
+ if timeout: signal.alarm(0)
131
+
132
+ # %% ../nbs/00_shell.ipynb #cdb9dc37
133
+ @patch
134
+ def _run_res(self:CaptureShell, result, c, raw_cell):
135
+ "Package a cell `result` and its captured output `c` as the `AttrDict` rendering uses"
136
+ # TODO what if there's a comment?
137
+ semic = raw_cell.rstrip().endswith(';') and not raw_cell.lstrip().startswith('%%')
138
+ e = result.error_in_exec or result.error_before_exec
139
+ if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
140
+ e.args = (f"{e} A cell magic (%%) must start the cell; remove or move the lines above it.",)
141
+ return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr, display_objects=c.outputs,
142
+ exception=e, quiet=semic)
143
+
144
+ # %% ../nbs/00_shell.ipynb #5bc0e776
145
+ @patch
146
+ def _run(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
147
+ stdout=True, stderr=True, display=True, timeout=None, verbose=False):
148
+ "Captured execution: run `raw_cell` with output capture and optional timeout, returning an `AttrDict`"
149
+ with self._captured(stdout, stderr, display, timeout, verbose) as c:
150
+ result = super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
151
+ return self._run_res(result, c, raw_cell)
152
+
153
+ # %% ../nbs/00_shell.ipynb #bfdb84a4
154
+ @patch
155
+ async def arun_cell(
156
+ self:CaptureShell,
157
+ raw_cell:str, # Python/IPython source for one cell
158
+ store_history:bool=False, # Store the cell in IPython's history?
159
+ silent:bool=False, # Suppress displayhook and `post_run_cell` event?
160
+ shell_futures:bool=True, # Share `__future__` imports with the shell?
161
+ cell_id=None, # Optional cell id, passed through to `run_cell_async`
162
+ ):
163
+ "Async `run_cell`: transform, await `run_cell_async` on the calling loop, and fire the post-execute events"
164
+ preprocessing_exc_tuple = None
165
+ try: transformed_cell = self.transform_cell(raw_cell)
166
+ except Exception:
167
+ transformed_cell = raw_cell
168
+ preprocessing_exc_tuple = sys.exc_info()
169
+ result = None
170
+ try: result = await self.run_cell_async(raw_cell, store_history, silent, shell_futures=shell_futures,
171
+ transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple, cell_id=cell_id)
172
+ finally:
173
+ self.events.trigger('post_execute')
174
+ if not silent: self.events.trigger('post_run_cell', result)
175
+ return result
176
+
177
+ # %% ../nbs/00_shell.ipynb #1483d0f2
178
+ @patch
179
+ async def _run_async(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
180
+ stdout=True, stderr=True, display=True, timeout=None, verbose=False):
181
+ "Async `_run`: awaits the cell on the calling event loop, so `raw_cell` may use top-level `await`"
182
+ with self._captured(stdout, stderr, display, timeout, verbose) as c:
183
+ result = await self.arun_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
184
+ return self._run_res(result, c, raw_cell)
185
+
134
186
  # %% ../nbs/00_shell.ipynb #a05e1b43
135
187
  @patch
136
188
  def load_profile(self:CaptureShell, name='default'):
@@ -209,13 +261,26 @@ def run(
209
261
  @patch
210
262
  async def run_async(
211
263
  self:CaptureShell,
212
- code: str, # Python/IPython code to run
213
- stdout=True, # Capture stdout and save as output?
214
- stderr=True, # Capture stderr and save as output?
264
+ code:str, # Python/IPython code to run
265
+ stdout=True, # Capture stdout and save as output?
266
+ stderr=True, # Capture stderr and save as output?
215
267
  timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
216
268
  verbose:bool=False # Show stdout/stderr during execution
217
269
  ):
218
- return self.run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
270
+ "Async `run`: awaits the cell on the calling event loop, so `code` may use top-level `await`"
271
+ res = await self._run_async(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
272
+ self.result = res.result.result
273
+ self.exc = res.exception
274
+ return _out_nb(res, self.display_formatter)
275
+
276
+ # %% ../nbs/00_shell.ipynb #16013a92
277
+ @patch
278
+ def showtraceback(self:CaptureShell, *args, **kwargs):
279
+ "A captured run reports its exception structurally; IPython's printed traceback would be a colored duplicate in the stream"
280
+
281
+ @patch
282
+ def showsyntaxerror(self:CaptureShell, *args, **kwargs):
283
+ "Like `showtraceback`"
219
284
 
220
285
  # %% ../nbs/00_shell.ipynb #f698a432
221
286
  def _pre(s, xtra=''): return f"<pre {xtra}><code>{escape(s)}</code></pre>"
@@ -344,69 +409,15 @@ def prettytb(self:CaptureShell,
344
409
  fname_str = f' in {fname}' if fname else ''
345
410
  return f"{type(self.exc).__name__}{fname_str}:\n{_fence}\n{cell_str}\n"
346
411
 
347
- # %% ../nbs/00_shell.ipynb #de6bd9f6
348
- def _is_exported(cell): return cell.has_directive('export') or cell.has_directive('exports')
349
- def _is_noeval(cell):
350
- return 'nbdev_export'+'(' in cell.source or (cell.directive('eval') or '').lower()=='false'
351
-
352
- def select_cells(
353
- nb, # A notebook read with `read_nb`
354
- msgid:str=None, # Cell id, or unique prefix, to match
355
- above:bool=False, # Include the matched cell and all cells above it?
356
- below:bool=False, # Include the matched cell and all cells below it?
357
- all:bool=False, # Include all code cells (ignores `msgid`)?
358
- exported:bool=False, # Only cells with `#| export` or `#| exports`?
359
- skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
360
- ):
361
- "Select code cells from `nb` by cell id or unique prefix"
362
- cells = [o for o in nb.cells if o.cell_type=='code']
363
- if not all:
364
- if not msgid: raise ValueError('`msgid` required unless `all=True`')
365
- idxs = [i for i,o in enumerate(cells) if str(o.id).startswith(msgid)]
366
- if not idxs: raise ValueError(f'No code cell id starting with {msgid!r}')
367
- if len(idxs)>1: raise ValueError(f'Multiple code cell ids start with {msgid!r}: {", ".join(str(cells[i].id) for i in idxs)}')
368
- idx = idxs[0]
369
- if above: cells = cells[:idx+1]
370
- elif below: cells = cells[idx:]
371
- else: cells = [cells[idx]]
372
- if exported: cells = [o for o in cells if _is_exported(o)]
373
- if skip_noeval: cells = [o for o in cells if not _is_noeval(o)]
374
- return cells
375
-
376
412
  # %% ../nbs/00_shell.ipynb #9c16e245
377
413
  from fastcore.nbio import render_text
378
414
 
379
- # %% ../nbs/00_shell.ipynb #ec223d10
415
+ # %% ../nbs/00_shell.ipynb #31536fa0
380
416
  @patch
381
- def nbopen(self:CaptureShell, fname:str|Path):
382
- "Set the default notebook for `nbrun`"
383
- fname = Path(fname)
384
- if not fname.exists(): raise FileNotFoundError(fname)
385
- self._nbrun_fname = fname
386
-
387
- @patch
388
- def nbrun(
389
- self:CaptureShell,
390
- *msgids:str, # Cell id prefixes to run, in the order given
391
- fname:str|Path=None, # Notebook path (defaults to last `nbopen`)
392
- above:bool=False, # Also run all cells above the match?
393
- below:bool=False, # Also run all cells below the match?
394
- all:bool=False, # Run all code cells?
395
- exported:bool=False, # Only cells with `#| export` or `#| exports`?
396
- skip_noeval:bool=False, # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
397
- stop_on_error:bool=True, # Stop after the first cell whose run errors?
398
- ):
399
- "Run cell(s) from a notebook by id prefix, printing rendered outputs"
400
- fname = ifnone(fname, getattr(self,'_nbrun_fname',None))
401
- if not fname: raise ValueError('No `fname` passed and no notebook opened with `nbopen`')
402
- self.nbopen(fname)
403
- nb = read_nb(fname)
404
- if all or not msgids: msgids = (None,)
405
- for msgid in msgids:
406
- for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
407
- outs = self.run(cell.source)
408
- if res := render_text(outs): print(f'--- {cell.id} ---\n{res}')
409
- if stop_on_error and any(o.get('output_type')=='error' for o in outs): return
417
+ @delegates(CaptureShell.run)
418
+ def run_text(self:CaptureShell, code, **kwargs):
419
+ "Run `code`, returning its outputs rendered as concise text: what a notebook's output area shows"
420
+ return render_text(self.run(code, **kwargs))
410
421
 
411
422
  # %% ../nbs/00_shell.ipynb #1227c8b1
412
423
  @call_parse
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.9
3
+ Version: 0.2.10
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -15,7 +15,7 @@ Classifier: Programming Language :: Python :: 3 :: Only
15
15
  Requires-Python: >=3.7
16
16
  Description-Content-Type: text/markdown
17
17
  License-File: LICENSE
18
- Requires-Dist: fastcore>=2.1.2
18
+ Requires-Dist: fastcore>=2.1.17
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -1,4 +1,4 @@
1
- fastcore>=2.1.2
1
+ fastcore>=2.1.17
2
2
  ipython
3
3
 
4
4
  [dev]
@@ -12,7 +12,7 @@ license = {text = "Apache-2.0"}
12
12
  authors = [{name = "Jeremy Howard", email = "j@fast.ai"}]
13
13
  keywords = ['some', 'keywords']
14
14
  classifiers = ["Natural Language :: English", "Intended Audience :: Developers", "Development Status :: 2 - Pre-Alpha", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only"]
15
- dependencies = ['fastcore>=2.1.2', 'ipython']
15
+ dependencies = ['fastcore>=2.1.17', 'ipython']
16
16
 
17
17
  [project.urls]
18
18
  Repository = "https://github.com/AnswerDotAI/execnb/"
@@ -1 +0,0 @@
1
- __version__ = "0.2.9"
File without changes
File without changes
File without changes
File without changes