execnb 0.2.10__tar.gz → 0.3.1__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.10
3
+ Version: 0.3.1
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.17
18
+ Requires-Dist: fastcore>=2.2.5
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -28,8 +28,6 @@ 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) [![Deploy to GitHub Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
32
-
33
31
  ## Install
34
32
 
35
33
  Either:
@@ -44,7 +42,7 @@ or if you use conda:
44
42
 
45
43
  ## How to use
46
44
 
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):
45
+ 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). The API is async, so `await` the run from a notebook or async code, or wrap it in [`asyncio.run`](https://docs.python.org/3/library/asyncio-runner.html#asyncio.run) at a sync entry point:
48
46
 
49
47
  ``` python
50
48
  from execnb.shell import *
@@ -54,7 +52,7 @@ from fastcore.nbio import *
54
52
 
55
53
  ``` python
56
54
  s = CaptureShell()
57
- s.run('1+1')
55
+ await s.run('1+1')
58
56
  ```
59
57
 
60
58
  [{'data': {'text/plain': ['2']},
@@ -66,7 +64,7 @@ To execute a notebook and save it with outputs filled in, use [`CaptureShell.exe
66
64
 
67
65
  ``` python
68
66
  try:
69
- s.execute('../tests/clean.ipynb', 'tmp.ipynb')
67
+ await s.execute('../tests/clean.ipynb', 'tmp.ipynb')
70
68
  print(read_nb('tmp.ipynb').cells[1].outputs)
71
69
  finally: Path('tmp.ipynb').unlink()
72
70
  ```
@@ -3,8 +3,6 @@
3
3
 
4
4
  <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
5
 
6
- [![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)
7
-
8
6
  ## Install
9
7
 
10
8
  Either:
@@ -19,7 +17,7 @@ or if you use conda:
19
17
 
20
18
  ## How to use
21
19
 
22
- 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):
20
+ 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). The API is async, so `await` the run from a notebook or async code, or wrap it in [`asyncio.run`](https://docs.python.org/3/library/asyncio-runner.html#asyncio.run) at a sync entry point:
23
21
 
24
22
  ``` python
25
23
  from execnb.shell import *
@@ -29,7 +27,7 @@ from fastcore.nbio import *
29
27
 
30
28
  ``` python
31
29
  s = CaptureShell()
32
- s.run('1+1')
30
+ await s.run('1+1')
33
31
  ```
34
32
 
35
33
  [{'data': {'text/plain': ['2']},
@@ -41,7 +39,7 @@ To execute a notebook and save it with outputs filled in, use [`CaptureShell.exe
41
39
 
42
40
  ``` python
43
41
  try:
44
- s.execute('../tests/clean.ipynb', 'tmp.ipynb')
42
+ await s.execute('../tests/clean.ipynb', 'tmp.ipynb')
45
43
  print(read_nb('tmp.ipynb').cells[1].outputs)
46
44
  finally: Path('tmp.ipynb').unlink()
47
45
  ```
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -8,11 +8,12 @@ d = { 'settings': { 'branch': 'main',
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
10
  'execnb.shell.CaptureShell._captured': ('shell.html#captureshell._captured', 'execnb/shell.py'),
11
+ 'execnb.shell.CaptureShell._reap': ('shell.html#captureshell._reap', 'execnb/shell.py'),
11
12
  'execnb.shell.CaptureShell._run': ('shell.html#captureshell._run', 'execnb/shell.py'),
12
13
  'execnb.shell.CaptureShell._run_async': ('shell.html#captureshell._run_async', 'execnb/shell.py'),
13
14
  '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'),
15
15
  'execnb.shell.CaptureShell.cell': ('shell.html#captureshell.cell', 'execnb/shell.py'),
16
+ 'execnb.shell.CaptureShell.close': ('shell.html#captureshell.close', 'execnb/shell.py'),
16
17
  'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
17
18
  'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
18
19
  'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
@@ -20,8 +21,6 @@ d = { 'settings': { 'branch': 'main',
20
21
  'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
21
22
  'execnb.shell.CaptureShell.run': ('shell.html#captureshell.run', 'execnb/shell.py'),
22
23
  'execnb.shell.CaptureShell.run_all': ('shell.html#captureshell.run_all', 'execnb/shell.py'),
23
- 'execnb.shell.CaptureShell.run_async': ('shell.html#captureshell.run_async', 'execnb/shell.py'),
24
- 'execnb.shell.CaptureShell.run_cell': ('shell.html#captureshell.run_cell', 'execnb/shell.py'),
25
24
  'execnb.shell.CaptureShell.run_text': ('shell.html#captureshell.run_text', 'execnb/shell.py'),
26
25
  'execnb.shell.CaptureShell.set_path': ('shell.html#captureshell.set_path', 'execnb/shell.py'),
27
26
  'execnb.shell.CaptureShell.showsyntaxerror': ('shell.html#captureshell.showsyntaxerror', 'execnb/shell.py'),
@@ -41,12 +40,14 @@ d = { 'settings': { 'branch': 'main',
41
40
  'execnb.shell._false': ('shell.html#_false', 'execnb/shell.py'),
42
41
  'execnb.shell._format_mimedata': ('shell.html#_format_mimedata', 'execnb/shell.py'),
43
42
  'execnb.shell._mk_out': ('shell.html#_mk_out', 'execnb/shell.py'),
43
+ 'execnb.shell._no_stdin': ('shell.html#_no_stdin', 'execnb/shell.py'),
44
44
  'execnb.shell._out_exc': ('shell.html#_out_exc', 'execnb/shell.py'),
45
45
  'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
46
46
  'execnb.shell._out_stream': ('shell.html#_out_stream', 'execnb/shell.py'),
47
47
  'execnb.shell._pre': ('shell.html#_pre', 'execnb/shell.py'),
48
48
  'execnb.shell._profile_cfg': ('shell.html#_profile_cfg', 'execnb/shell.py'),
49
49
  'execnb.shell._strip': ('shell.html#_strip', 'execnb/shell.py'),
50
+ 'execnb.shell._task_stacks': ('shell.html#_task_stacks', 'execnb/shell.py'),
50
51
  'execnb.shell.exec_nb': ('shell.html#exec_nb', 'execnb/shell.py'),
51
52
  'execnb.shell.find_output': ('shell.html#find_output', 'execnb/shell.py'),
52
53
  'execnb.shell.format_exc': ('shell.html#format_exc', 'execnb/shell.py'),
@@ -14,8 +14,8 @@ from fastcore.meta import delegates
14
14
  from fastcore.script import call_parse
15
15
  from fastcore.ansi import strip_ansi
16
16
 
17
- import multiprocessing,types,traceback,signal
18
- from contextlib import contextmanager
17
+ import asyncio,io,multiprocessing,threading,types,traceback,builtins
18
+ from contextlib import contextmanager,suppress
19
19
  try:
20
20
  if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
21
21
  except RuntimeError: pass # if re-running cell
@@ -24,7 +24,7 @@ from traitlets.config import Config
24
24
  from traitlets.config.loader import PyFileConfigLoader
25
25
  from IPython.paths import get_ipython_dir
26
26
  from IPython.core.interactiveshell import InteractiveShell, ExecutionInfo, ExecutionResult
27
- from IPython.core.error import UsageError
27
+ from IPython.core.error import UsageError, StdinNotImplementedError
28
28
  from IPython.core.displayhook import DisplayHook
29
29
  from IPython.utils.capture import capture_output
30
30
  from IPython.core.completer import IPCompleter,provisionalcompleter
@@ -82,6 +82,9 @@ class CaptureShell(InteractiveShell):
82
82
  self.history_manager.enabled = history
83
83
  self.timeout = timeout
84
84
  self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
85
+ self.loop = asyncio.new_event_loop()
86
+ self._thread = threading.Thread(target=self.loop.run_forever, daemon=True, name='CaptureShell-loop')
87
+ self._thread.start()
85
88
  if path: self.set_path(path)
86
89
  self.display_formatter.active = True
87
90
  if not in_notebook(): InteractiveShell._instance = self
@@ -98,90 +101,55 @@ class CaptureShell(InteractiveShell):
98
101
  "Add `path` to python path, or `path.parent` if it's a file"
99
102
  path = Path(path)
100
103
  if path.is_file(): path = path.parent
101
- self._run(f"import sys; sys.path.insert(0, '{path.as_posix()}')")
104
+ self._run(f"import sys\nif '{path.as_posix()}' not in sys.path: sys.path.insert(0, '{path.as_posix()}')")
102
105
 
103
- def enable_gui(self, gui=None): pass
104
-
105
- # %% ../nbs/00_shell.ipynb #93adf867
106
- @patch
107
- def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
108
- stdout=True, stderr=True, display=True, timeout=None, verbose=False):
109
- if self._nested: return super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
110
- return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
111
- stdout=stdout, stderr=stderr, display=display, timeout=timeout, verbose=verbose)
106
+ def close(self):
107
+ "Stop the shell's loop and thread; the shell can no longer run cells"
108
+ self.loop.call_soon_threadsafe(self.loop.stop)
109
+ self._thread.join(1)
112
110
 
111
+ def enable_gui(self, gui=None): pass
113
112
 
114
113
  # %% ../nbs/00_shell.ipynb #6f0cac34
114
+ def _no_stdin(*args, **kw): raise StdinNotImplementedError('input() is not supported in a captured run')
115
+
115
116
  @patch
116
117
  @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)
118
+ def _captured(self:CaptureShell, stdout=True, stderr=True, display=True, verbose=False):
119
+ "Output capture and stdin blocking around one cell run"
120
+ prev_input = builtins.input
121
+ builtins.input = _no_stdin
124
122
  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)
123
+ with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c: yield c
124
+ finally: builtins.input = prev_input
131
125
 
132
126
  # %% ../nbs/00_shell.ipynb #cdb9dc37
133
127
  @patch
134
- def _run_res(self:CaptureShell, result, c, raw_cell):
128
+ def _run_res(self:CaptureShell, result, c):
135
129
  "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
130
  e = result.error_in_exec or result.error_before_exec
139
131
  if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
140
132
  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)
133
+ return AttrDict(result=result, stdout=c.stdout, stderr=c.stderr, display_objects=c.outputs, exception=e)
143
134
 
144
135
  # %% ../nbs/00_shell.ipynb #5bc0e776
145
136
  @patch
146
137
  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:
138
+ stdout=True, stderr=True, display=True, verbose=False):
139
+ "Sync captured run through IPython's own `run_cell` entry, on the calling thread, for constructor-time setup lines"
140
+ with self._captured(stdout, stderr, display, verbose) as c:
150
141
  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
142
+ return self._run_res(result, c)
176
143
 
177
144
  # %% ../nbs/00_shell.ipynb #1483d0f2
178
145
  @patch
179
146
  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)
147
+ stdout=True, stderr=True, display=True, verbose=False):
148
+ "Async `_run`: awaits the cell via `fastcore.nbio.run_cell`, so `raw_cell` may use top-level `await`; runs only on the shell's own loop"
149
+ with self._captured(stdout, stderr, display, verbose) as c:
150
+ result = await run_cell(self, raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
151
+ return self._run_res(result, c)
152
+
185
153
 
186
154
  # %% ../nbs/00_shell.ipynb #a05e1b43
187
155
  @patch
@@ -210,11 +178,8 @@ def format_exc(e):
210
178
  class NbResult(list): pass
211
179
 
212
180
  # %% ../nbs/00_shell.ipynb #26bf9161
213
- def _out_stream(text, name): return dict(name=name, output_type='stream', text=text.splitlines(True))
214
- def _out_exc(e):
215
- ename = type(e).__name__
216
- tb = traceback.extract_tb(e.__traceback__)#.format()
217
- return dict(ename=str(ename), evalue=str(e), output_type='error', traceback=format_exc(e))
181
+ def _out_stream(text, name): return mk_stream(name, text.splitlines(True))
182
+ def _out_exc(e): return mk_error(format_exc(e), ename=type(e).__name__, evalue=str(e))
218
183
 
219
184
  def _format_mimedata(k, v):
220
185
  "Format mime-type keyed data consistently with Jupyter"
@@ -235,12 +200,17 @@ def _out_nb(o, fmt):
235
200
  if o.exception: res.append(_out_exc(o.exception))
236
201
  res.result = o.result.result
237
202
  for x in o.display_objects: res.append(_mk_out(x.data, x.metadata))
238
- if res.result is not None and not o.quiet: res.append(_mk_out(*fmt.format(res.result), 'execute_result'))
239
- if 'execution_count' not in o: o['execution_count']=None
203
+ if res.result is not None: res.append(_mk_out(*fmt.format(res.result), 'execute_result'))
240
204
  for p in res:
241
- if p["output_type"]=="execute_result": p['execution_count'] = o['execution_count']
205
+ if p["output_type"]=="execute_result": p['execution_count'] = o.result.execution_count
242
206
  return res
243
207
 
208
+ # %% ../nbs/00_shell.ipynb #01307010
209
+ def _task_stacks(ts):
210
+ buf = io.StringIO()
211
+ for t in ts: t.print_stack(file=buf)
212
+ return buf.getvalue()
213
+
244
214
  # %% ../nbs/00_shell.ipynb #242f732f
245
215
  @patch
246
216
  def run(
@@ -248,27 +218,20 @@ def run(
248
218
  code:str, # Python/IPython code to run
249
219
  stdout=True, # Capture stdout and save as output?
250
220
  stderr=True, # Capture stderr and save as output?
251
- timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
252
- verbose:bool=False # Show stdout/stderr during execution
221
+ timeout:Optional[int]=None, # Seconds before the run times out (None: `self.timeout`)
222
+ verbose:bool=False, # Show stdout/stderr during execution
223
+ grace:float=5 # Seconds to wait for cancellation after a timeout
253
224
  ):
254
- "Run `code`, returning a list of all outputs in Jupyter notebook format"
255
- res = self._run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
256
- self.result = res.result.result
257
- self.exc = res.exception
258
- return _out_nb(res, self.display_formatter)
259
-
260
- # %% ../nbs/00_shell.ipynb #eaa11df9
261
- @patch
262
- async def run_async(
263
- self:CaptureShell,
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?
267
- timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
268
- verbose:bool=False # Show stdout/stderr during execution
269
- ):
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)
225
+ "Run `code` on the shell's loop, returning a list of all outputs in Jupyter notebook format"
226
+ if timeout is None: timeout = self.timeout
227
+ fut = asyncio.run_coroutine_threadsafe(self._run_async(code, store_history=True, stdout=stdout, stderr=stderr, verbose=verbose), self.loop)
228
+ try: res = fut.result(timeout)
229
+ except TimeoutError:
230
+ stacks = _task_stacks(asyncio.all_tasks(self.loop))
231
+ fut.cancel()
232
+ with suppress(Exception): fut.result(grace)
233
+ self.exc = e = TimeoutError(f'Timed out after {timeout}s:\n{code}' + (f'\n\nTasks pending at timeout:\n{stacks}' if stacks else ''))
234
+ return NbResult([_out_exc(e)])
272
235
  self.result = res.result.result
273
236
  self.exc = res.exception
274
237
  return _out_nb(res, self.display_formatter)
@@ -319,12 +282,14 @@ def render_outputs(outputs, ansi_renderer=_strip, include_imgs=True, pygments=Fa
319
282
 
320
283
  # %% ../nbs/00_shell.ipynb #c6176b9e
321
284
  @patch
322
- def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
323
- "Run `cell`, skipping if not code, and store outputs back in cell"
285
+ def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False, timeout=None):
286
+ "Run `cell`, skipping if not code, and store outputs (and the execution count) back in cell"
324
287
  if cell.cell_type!='code': return
325
288
  self._cell_idx = cell.idx_ + 1
326
- outs = self.run(cell.source, verbose=verbose)
289
+ outs = self.run(cell.source, stdout=stdout, stderr=stderr, verbose=verbose, timeout=timeout)
327
290
  cell.outputs = _dict2obj(outs) if outs else []
291
+ cell.execution_count = self.execution_count-1 # the count this run used: the shell has already advanced
292
+
328
293
 
329
294
  # %% ../nbs/00_shell.ipynb #008c0cef
330
295
  def find_output(
@@ -355,6 +320,21 @@ def out_error(outp):
355
320
  # %% ../nbs/00_shell.ipynb #60a25f27
356
321
  def _false(o): return False
357
322
 
323
+ @patch
324
+ def _reap(self:CaptureShell,
325
+ before, # Tasks that existed before the run: never touched
326
+ grace:float=5 # Seconds to wait for cancellation before giving up
327
+ ):
328
+ "Cancel tasks a run left behind on the shell's loop, returning any that refuse to die"
329
+ ts = asyncio.all_tasks(self.loop) - before
330
+ if not ts: return []
331
+ async def _cancel():
332
+ for t in ts: t.cancel()
333
+ done,pend = await asyncio.wait(ts, timeout=grace)
334
+ return list(pend)
335
+ try: return asyncio.run_coroutine_threadsafe(_cancel(), self.loop).result(grace+1)
336
+ except TimeoutError: return list(ts)
337
+
358
338
  @patch
359
339
  def run_all(
360
340
  self:CaptureShell,
@@ -364,15 +344,20 @@ def run_all(
364
344
  postproc:callable=_false, # Called after each cell is executed
365
345
  inject_code:str|None=None, # Code to inject into a cell
366
346
  inject_idx:int=0, # Cell to replace with `inject_code`
367
- verbose:bool=False # Show stdout/stderr during execution
347
+ verbose:bool=False, # Show stdout/stderr during execution
348
+ cell_timeout:int=None, # Seconds before each cell times out (None: no limit)
349
+ grace:float=5 # Seconds to wait for cancellation before giving up
368
350
  ):
369
- "Run all cells in `nb`, stopping at first exception if `exc_stop`"
351
+ "Run all cells in `nb`, stopping at first exception if `exc_stop`; tasks a run leaves behind are cancelled, with survivors in `self.leaks`"
370
352
  if inject_code is not None: nb.cells[inject_idx].source = inject_code
353
+ before = asyncio.all_tasks(self.loop)
371
354
  for cell in nb.cells:
372
355
  if not preproc(cell):
373
- self.cell(cell, verbose=verbose)
356
+ self.cell(cell, verbose=verbose, timeout=cell_timeout)
374
357
  postproc(cell)
375
- if self.exc and exc_stop: raise self.exc from None
358
+ if self.exc and exc_stop: break
359
+ self.leaks = self._reap(before, grace)
360
+ if self.exc and exc_stop: raise self.exc from None
376
361
 
377
362
  # %% ../nbs/00_shell.ipynb #70808010
378
363
  @patch
@@ -386,7 +371,8 @@ def execute(
386
371
  inject_code:str|None=None, # Code to inject into a cell
387
372
  inject_path:str|Path|None=None, # Path to file containing code to inject into a cell
388
373
  inject_idx:int=0, # Cell to replace with `inject_code`
389
- verbose:bool=False # Show stdout/stderr during execution
374
+ verbose:bool=False, # Show stdout/stderr during execution
375
+ cell_timeout:int=None # Seconds before each cell times out (None: no limit)
390
376
  ):
391
377
  "Execute notebook from `src` and save with outputs to `dest"
392
378
  nb = read_nb(src)
@@ -394,7 +380,7 @@ def execute(
394
380
  self.set_path(Path(src).parent.resolve())
395
381
  if inject_path is not None: inject_code = Path(inject_path).read_text()
396
382
  self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
397
- inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
383
+ inject_code=inject_code, inject_idx=inject_idx, verbose=verbose, cell_timeout=cell_timeout)
398
384
  if dest: write_nb(nb, dest)
399
385
 
400
386
  # %% ../nbs/00_shell.ipynb #694161cb
@@ -402,6 +388,7 @@ def execute(
402
388
  def prettytb(self:CaptureShell,
403
389
  fname:str|Path=None): # filename to print alongside the traceback
404
390
  "Show a pretty traceback for notebooks, optionally printing `fname`."
391
+ if self.exc is None: return ""
405
392
  fname = fname if fname else self._fname
406
393
  _fence = '='*75
407
394
  cell_intro_str = f"While Executing Cell #{self._cell_idx}:" if self._cell_idx else "While Executing:"
@@ -428,11 +415,12 @@ def exec_nb(
428
415
  inject_code:str=None, # Code to inject into a cell
429
416
  inject_path:str=None, # Path to file containing code to inject into a cell
430
417
  inject_idx:int=0, # Cell to replace with `inject_code`
431
- verbose:bool=False # Show stdout/stderr during execution
418
+ verbose:bool=False, # Show stdout/stderr during execution
419
+ cell_timeout:int=None # Seconds before each cell times out (None: no limit)
432
420
  ):
433
421
  "Execute notebook from `src` and save with outputs to `dest`"
434
422
  CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
435
- inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
423
+ inject_path=inject_path, inject_idx=inject_idx, verbose=verbose, cell_timeout=cell_timeout)
436
424
 
437
425
  # %% ../nbs/00_shell.ipynb #c44963a0
438
426
  class SmartCompleter(IPCompleter):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.10
3
+ Version: 0.3.1
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.17
18
+ Requires-Dist: fastcore>=2.2.5
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -28,8 +28,6 @@ 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) [![Deploy to GitHub Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
32
-
33
31
  ## Install
34
32
 
35
33
  Either:
@@ -44,7 +42,7 @@ or if you use conda:
44
42
 
45
43
  ## How to use
46
44
 
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):
45
+ 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). The API is async, so `await` the run from a notebook or async code, or wrap it in [`asyncio.run`](https://docs.python.org/3/library/asyncio-runner.html#asyncio.run) at a sync entry point:
48
46
 
49
47
  ``` python
50
48
  from execnb.shell import *
@@ -54,7 +52,7 @@ from fastcore.nbio import *
54
52
 
55
53
  ``` python
56
54
  s = CaptureShell()
57
- s.run('1+1')
55
+ await s.run('1+1')
58
56
  ```
59
57
 
60
58
  [{'data': {'text/plain': ['2']},
@@ -66,7 +64,7 @@ To execute a notebook and save it with outputs filled in, use [`CaptureShell.exe
66
64
 
67
65
  ``` python
68
66
  try:
69
- s.execute('../tests/clean.ipynb', 'tmp.ipynb')
67
+ await s.execute('../tests/clean.ipynb', 'tmp.ipynb')
70
68
  print(read_nb('tmp.ipynb').cells[1].outputs)
71
69
  finally: Path('tmp.ipynb').unlink()
72
70
  ```
@@ -10,4 +10,5 @@ execnb.egg-info/SOURCES.txt
10
10
  execnb.egg-info/dependency_links.txt
11
11
  execnb.egg-info/entry_points.txt
12
12
  execnb.egg-info/requires.txt
13
- execnb.egg-info/top_level.txt
13
+ execnb.egg-info/top_level.txt
14
+ tests/test_shell.py
@@ -1,4 +1,4 @@
1
- fastcore>=2.1.17
1
+ fastcore>=2.2.5
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.17', 'ipython']
15
+ dependencies = ['fastcore>=2.2.5', 'ipython']
16
16
 
17
17
  [project.urls]
18
18
  Repository = "https://github.com/AnswerDotAI/execnb/"
@@ -0,0 +1,34 @@
1
+ """Nested execution: a cell driving `fastcore.nbio.run_cell` against a shell, run on the
2
+ shell's own loop. Pins that inner-run assignments persist in the right namespace and errors
3
+ stay structural."""
4
+ from IPython.core.interactiveshell import InteractiveShell
5
+ from execnb.shell import CaptureShell
6
+
7
+
8
+ def test_nested_run_separate_shell():
9
+ "Inner runs against a second shell: assignments persist in the inner ns, visible during and after the outer cell"
10
+ k = CaptureShell(mpl_format=None)
11
+ k.user_ns['psh'] = InteractiveShell()
12
+ outs = k.run(
13
+ "from fastcore.nbio import run_cell\n"
14
+ "r1 = await run_cell(psh, 'zz = 5', silent=True)\n"
15
+ "r2 = await run_cell(psh, 'zz2 = zz+1', store_history=True)\n"
16
+ "ok = psh.user_ns.get('zz')==5 and psh.user_ns.get('zz2')==6")
17
+ assert not k.exc, outs
18
+ psh = k.user_ns['psh']
19
+ assert k.user_ns['ok'], 'inner assignments not visible inside the outer cell'
20
+ assert psh.user_ns.get('zz')==5 and psh.user_ns.get('zz2')==6, 'inner assignments lost after the outer cell'
21
+
22
+
23
+ def test_nested_run_self_shell():
24
+ "Inner runs against the outer shell itself via get_ipython(): assignments persist in its ns"
25
+ k = CaptureShell(mpl_format=None)
26
+ outs = k.run(
27
+ "from fastcore.nbio import run_cell\n"
28
+ "await run_cell(get_ipython(), 'qq = 7', silent=True)\n"
29
+ "await run_cell(get_ipython(), 'qq2 = qq+1', store_history=True)\n"
30
+ "inner_saw = get_ipython().user_ns.get('qq2')")
31
+ assert not k.exc, outs
32
+ assert k.user_ns.get('inner_saw')==8, 'inner runs did not see their own writes'
33
+ assert k.user_ns.get('qq')==7 and k.user_ns.get('qq2')==8, \
34
+ f"assignments lost after outer cell: qq={k.user_ns.get('qq')} qq2={k.user_ns.get('qq2')}"
@@ -1 +0,0 @@
1
- __version__ = "0.2.10"
File without changes
File without changes
File without changes