execnb 0.2.5__py3-none-any.whl → 0.2.7__py3-none-any.whl

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.
execnb/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.2.5"
1
+ __version__ = "0.2.7"
execnb/shell.py CHANGED
@@ -70,7 +70,7 @@ class CaptureShell(InteractiveShell):
70
70
  super().__init__(config=cfg)
71
71
  self.history_manager.enabled = history
72
72
  self.timeout = timeout
73
- self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
73
+ self.result,self.exc,self._cell_idx,self._fname,self._nested = None,None,None,None,False
74
74
  if path: self.set_path(path)
75
75
  self.display_formatter.active = True
76
76
  if not in_notebook(): InteractiveShell._instance = self
@@ -84,11 +84,22 @@ class CaptureShell(InteractiveShell):
84
84
  if profile: self.load_profile()
85
85
 
86
86
  def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
87
- stdout=True, stderr=True, display=True, verbose=False):
87
+ stdout=True, stderr=True, display=True, timeout=None, verbose=False):
88
+ "Captured execution: run `raw_cell` with output capture and optional timeout, returning an `AttrDict`"
88
89
  # TODO what if there's a comment?
89
- semic = raw_cell.rstrip().endswith(';')
90
- with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
91
- result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
90
+ semic = raw_cell.rstrip().endswith(';') and not raw_cell.lstrip().startswith('%%')
91
+ if not timeout: timeout = self.timeout
92
+ if timeout:
93
+ def handler(*args): raise TimeoutError()
94
+ signal.signal(signal.SIGALRM, handler)
95
+ signal.alarm(timeout)
96
+ try:
97
+ with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
98
+ old,self._nested = self._nested,True
99
+ try: result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
100
+ finally: self._nested = old
101
+ finally:
102
+ if timeout: signal.alarm(0)
92
103
  return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr, display_objects=c.outputs,
93
104
  exception=result.error_in_exec or result.error_before_exec, quiet=semic)
94
105
 
@@ -104,15 +115,10 @@ class CaptureShell(InteractiveShell):
104
115
  @patch
105
116
  def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
106
117
  stdout=True, stderr=True, display=True, timeout=None, verbose=False):
107
- if not timeout: timeout = self.timeout
108
- if timeout:
109
- def handler(*args): raise TimeoutError()
110
- signal.signal(signal.SIGALRM, handler)
111
- signal.alarm(timeout)
112
- try: return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
113
- stdout=stdout, stderr=stderr, display=display, verbose=verbose)
114
- finally:
115
- if timeout: signal.alarm(0)
118
+ if self._nested: return super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
119
+ return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
120
+ stdout=stdout, stderr=stderr, display=display, timeout=timeout, verbose=verbose)
121
+
116
122
 
117
123
  # %% ../nbs/00_shell.ipynb #a05e1b43
118
124
  @patch
@@ -174,26 +180,30 @@ def _out_nb(o, fmt):
174
180
 
175
181
  # %% ../nbs/00_shell.ipynb #242f732f
176
182
  @patch
177
- def run(self:CaptureShell,
183
+ def run(
184
+ self:CaptureShell,
178
185
  code:str, # Python/IPython code to run
179
186
  stdout=True, # Capture stdout and save as output?
180
187
  stderr=True, # Capture stderr and save as output?
181
188
  timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
182
- verbose:bool=False): # Show stdout/stderr during execution
189
+ verbose:bool=False # Show stdout/stderr during execution
190
+ ):
183
191
  "Run `code`, returning a list of all outputs in Jupyter notebook format"
184
- res = self.run_cell(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
192
+ res = self._run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
185
193
  self.result = res.result.result
186
194
  self.exc = res.exception
187
195
  return _out_nb(res, self.display_formatter)
188
196
 
189
197
  # %% ../nbs/00_shell.ipynb #eaa11df9
190
198
  @patch
191
- async def run_async(self:CaptureShell,
199
+ async def run_async(
200
+ self:CaptureShell,
192
201
  code: str, # Python/IPython code to run
193
202
  stdout=True, # Capture stdout and save as output?
194
203
  stderr=True, # Capture stderr and save as output?
195
204
  timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
196
- verbose:bool=False): # Show stdout/stderr during execution
205
+ verbose:bool=False # Show stdout/stderr during execution
206
+ ):
197
207
  return self.run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
198
208
 
199
209
  # %% ../nbs/00_shell.ipynb #f698a432
@@ -238,12 +248,13 @@ def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
238
248
  if cell.cell_type!='code': return
239
249
  self._cell_idx = cell.idx_ + 1
240
250
  outs = self.run(cell.source, verbose=verbose)
241
- if outs: cell.outputs = _dict2obj(outs)
251
+ cell.outputs = _dict2obj(outs) if outs else []
242
252
 
243
253
  # %% ../nbs/00_shell.ipynb #008c0cef
244
- def find_output(outp, # Output from `run`
254
+ def find_output(
255
+ outp, # Output from `run`
245
256
  ot='execute_result' # Output_type to find
246
- ):
257
+ ):
247
258
  "Find first output of type `ot` in `CaptureShell.run` output"
248
259
  return first(o for o in outp if o['output_type']==ot)
249
260
 
@@ -289,7 +300,8 @@ def run_all(
289
300
 
290
301
  # %% ../nbs/00_shell.ipynb #70808010
291
302
  @patch
292
- def execute(self:CaptureShell,
303
+ def execute(
304
+ self:CaptureShell,
293
305
  src:str|Path, # Notebook path to read from
294
306
  dest:str|None=None, # Notebook path to write to
295
307
  exc_stop:bool=False, # Stop on exceptions?
@@ -328,19 +340,21 @@ def _is_noeval(src):
328
340
 
329
341
  def select_cells(
330
342
  nb, # A notebook read with `read_nb`
331
- msgid:str=None, # Cell id prefix to match
343
+ msgid:str=None, # Cell id, or unique prefix, to match
332
344
  above:bool=False, # Include the matched cell and all cells above it?
333
345
  below:bool=False, # Include the matched cell and all cells below it?
334
346
  all:bool=False, # Include all code cells (ignores `msgid`)?
335
347
  exported:bool=False, # Only cells with `#| export` or `#| exports`?
336
348
  skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
337
349
  ):
338
- "Select code cells from `nb` by cell id prefix"
350
+ "Select code cells from `nb` by cell id or unique prefix"
339
351
  cells = [o for o in nb.cells if o.cell_type=='code']
340
352
  if not all:
341
353
  if not msgid: raise ValueError('`msgid` required unless `all=True`')
342
- idx = first(i for i,o in enumerate(cells) if str(o.id).startswith(msgid))
343
- if idx is None: raise ValueError(f'No code cell id starting with {msgid!r}')
354
+ idxs = [i for i,o in enumerate(cells) if str(o.id).startswith(msgid)]
355
+ if not idxs: raise ValueError(f'No code cell id starting with {msgid!r}')
356
+ if len(idxs)>1: raise ValueError(f'Multiple code cell ids start with {msgid!r}: {", ".join(str(cells[i].id) for i in idxs)}')
357
+ idx = idxs[0]
344
358
  if above: cells = cells[:idx+1]
345
359
  elif below: cells = cells[idx:]
346
360
  else: cells = [cells[idx]]
@@ -355,12 +369,14 @@ from fastcore.nbio import render_text
355
369
  @patch
356
370
  def nbopen(self:CaptureShell, fname:str|Path):
357
371
  "Set the default notebook for `nbrun`"
358
- self._nbrun_fname = Path(fname)
372
+ fname = Path(fname)
373
+ if not fname.exists(): raise FileNotFoundError(fname)
374
+ self._nbrun_fname = fname
359
375
 
360
376
  @patch
361
377
  def nbrun(
362
378
  self:CaptureShell,
363
- msgid:str=None, # Cell id prefix to run
379
+ *msgids:str, # Cell id prefixes to run, in the order given
364
380
  fname:str|Path=None, # Notebook path (defaults to last `nbopen`)
365
381
  above:bool=False, # Also run all cells above the match?
366
382
  below:bool=False, # Also run all cells below the match?
@@ -373,9 +389,11 @@ def nbrun(
373
389
  if not fname: raise ValueError('No `fname` passed and no notebook opened with `nbopen`')
374
390
  self.nbopen(fname)
375
391
  nb = read_nb(fname)
376
- for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
377
- res = render_text(self.run(cell.source))
378
- if res: print(f'--- {cell.id} ---\n{res}')
392
+ if all or not msgids: msgids = (None,)
393
+ for msgid in msgids:
394
+ for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
395
+ res = render_text(self.run(cell.source))
396
+ if res: print(f'--- {cell.id} ---\n{res}')
379
397
 
380
398
  # %% ../nbs/00_shell.ipynb #1227c8b1
381
399
  @call_parse
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.5
3
+ Version: 0.2.7
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>=1.10.4
18
+ Requires-Dist: fastcore>=1.12.27
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -28,9 +28,7 @@ Dynamic: license-file
28
28
 
29
29
  <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
30
30
 
31
- [![CI](https://github.com/fastai/execnb/actions/workflows/test.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/test.yaml)
32
- [![Deploy to GitHub
33
- Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
31
+ [![CI](https://github.com/fastai/execnb/actions/workflows/test.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/test.yaml) [![Deploy to GitHub Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
34
32
 
35
33
  ## Install
36
34
 
@@ -42,15 +40,11 @@ or if you use conda:
42
40
 
43
41
  conda install -c fastai execnb
44
42
 
45
- (You can replace `conda` with `mamba` in the line above if you have
46
- mamba installed.)
43
+ (You can replace `conda` with `mamba` in the line above if you have mamba installed.)
47
44
 
48
45
  ## How to use
49
46
 
50
- Use
51
- [`CaptureShell`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell)
52
- to run Jupyter code and capture notebook outputs, without running a
53
- Jupyter server (or even having it installed):
47
+ Use [`CaptureShell`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell) to run Jupyter code and capture notebook outputs, without running a Jupyter server (or even having it installed):
54
48
 
55
49
  ``` python
56
50
  from execnb.shell import *
@@ -68,8 +62,7 @@ s.run('1+1')
68
62
  'output_type': 'execute_result',
69
63
  'execution_count': None}]
70
64
 
71
- To execute a notebook and save it with outputs filled in, use
72
- [`CaptureShell.execute`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell.execute):
65
+ To execute a notebook and save it with outputs filled in, use [`CaptureShell.execute`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell.execute):
73
66
 
74
67
  ``` python
75
68
  try:
@@ -78,10 +71,9 @@ try:
78
71
  finally: Path('tmp.ipynb').unlink()
79
72
  ```
80
73
 
81
- [{'name': 'stdout', 'output_type': 'stream', 'text': ['1\n']}, {'data': {'text/plain': ['2']}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}]
74
+ [{'name': 'stdout', 'output_type': 'stream', 'text': '1\n'}, {'data': {'text/plain': '2'}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}]
82
75
 
83
- You can also execute notebooks from the command line with
84
- [`exec_nb`](https://AnswerDotAI.github.io/execnb/shell.html#exec_nb):
76
+ You can also execute notebooks from the command line with [`exec_nb`](https://AnswerDotAI.github.io/execnb/shell.html#exec_nb):
85
77
 
86
78
  ``` python
87
79
  !exec_nb --help
@@ -0,0 +1,9 @@
1
+ execnb/__init__.py,sha256=XHypfHSPdgXFKmOdoewn7czU670gt8InhHhzlP5j_aA,22
2
+ execnb/_modidx.py,sha256=hpN6T1XnbTJKPSZM9ap1ovDJkLVFfUk7dBuvPkeowIY,5623
3
+ execnb/shell.py,sha256=lPUmDeOUO64axxYdEgYuzsxUxnIq3VtCUrxLsM2WJzY,19446
4
+ execnb-0.2.7.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
+ execnb-0.2.7.dist-info/METADATA,sha256=P8cCnC8W_ezWL3xcWjZSFAMuBr9VqJ6OPksy8iDmUE8,3458
6
+ execnb-0.2.7.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ execnb-0.2.7.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
8
+ execnb-0.2.7.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
9
+ execnb-0.2.7.dist-info/RECORD,,
@@ -1,9 +0,0 @@
1
- execnb/__init__.py,sha256=Xsa3ayOMVkhUWm4t06YeyHE0apjpZefxLH4ylp0CDtU,22
2
- execnb/_modidx.py,sha256=hpN6T1XnbTJKPSZM9ap1ovDJkLVFfUk7dBuvPkeowIY,5623
3
- execnb/shell.py,sha256=ObiLOJLHFgzCOIA49jh6lmJ65w57cCu-HHDS-hnsRwk,18597
4
- execnb-0.2.5.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
- execnb-0.2.5.dist-info/METADATA,sha256=PKFKzvY3pESQXUjfvTifIM4tw3ZXSQvGwBGN4x8vmWI,3461
6
- execnb-0.2.5.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
- execnb-0.2.5.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
8
- execnb-0.2.5.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
9
- execnb-0.2.5.dist-info/RECORD,,
File without changes