execnb 0.3.0__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.3.0
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
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -8,10 +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
15
  'execnb.shell.CaptureShell.cell': ('shell.html#captureshell.cell', 'execnb/shell.py'),
16
+ 'execnb.shell.CaptureShell.close': ('shell.html#captureshell.close', 'execnb/shell.py'),
15
17
  'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
16
18
  'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
17
19
  'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
@@ -45,6 +47,7 @@ d = { 'settings': { 'branch': 'main',
45
47
  'execnb.shell._pre': ('shell.html#_pre', 'execnb/shell.py'),
46
48
  'execnb.shell._profile_cfg': ('shell.html#_profile_cfg', 'execnb/shell.py'),
47
49
  'execnb.shell._strip': ('shell.html#_strip', 'execnb/shell.py'),
50
+ 'execnb.shell._task_stacks': ('shell.html#_task_stacks', 'execnb/shell.py'),
48
51
  'execnb.shell.exec_nb': ('shell.html#exec_nb', 'execnb/shell.py'),
49
52
  'execnb.shell.find_output': ('shell.html#find_output', 'execnb/shell.py'),
50
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,builtins
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
@@ -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
@@ -100,6 +103,11 @@ class CaptureShell(InteractiveShell):
100
103
  if path.is_file(): path = path.parent
101
104
  self._run(f"import sys\nif '{path.as_posix()}' not in sys.path: sys.path.insert(0, '{path.as_posix()}')")
102
105
 
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)
110
+
103
111
  def enable_gui(self, gui=None): pass
104
112
 
105
113
  # %% ../nbs/00_shell.ipynb #6f0cac34
@@ -107,23 +115,13 @@ def _no_stdin(*args, **kw): raise StdinNotImplementedError('input() is not suppo
107
115
 
108
116
  @patch
109
117
  @contextmanager
110
- def _captured(self:CaptureShell, stdout=True, stderr=True, display=True, timeout=None, verbose=False):
111
- "Output capture, stdin blocking, and optional SIGALRM timeout around one cell run"
112
- if not timeout: timeout = self.timeout
113
- prev_alarm = None
114
- if timeout:
115
- def handler(*args): raise TimeoutError()
116
- prev_alarm = signal.signal(signal.SIGALRM, handler)
117
- 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"
118
120
  prev_input = builtins.input
119
121
  builtins.input = _no_stdin
120
122
  try:
121
123
  with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c: yield c
122
- finally:
123
- builtins.input = prev_input
124
- if timeout:
125
- signal.alarm(0)
126
- signal.signal(signal.SIGALRM, prev_alarm)
124
+ finally: builtins.input = prev_input
127
125
 
128
126
  # %% ../nbs/00_shell.ipynb #cdb9dc37
129
127
  @patch
@@ -137,18 +135,18 @@ def _run_res(self:CaptureShell, result, c):
137
135
  # %% ../nbs/00_shell.ipynb #5bc0e776
138
136
  @patch
139
137
  def _run(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
140
- stdout=True, stderr=True, display=True, timeout=None, verbose=False):
141
- "Sync captured run through IPython's own `run_cell` entry, for constructor-time setup lines that run before any loop exists"
142
- 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:
143
141
  result = super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
144
142
  return self._run_res(result, c)
145
143
 
146
144
  # %% ../nbs/00_shell.ipynb #1483d0f2
147
145
  @patch
148
146
  async def _run_async(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
149
- stdout=True, stderr=True, display=True, timeout=None, verbose=False):
150
- "Async `_run`: awaits the cell via `fastcore.nbio.run_cell` on the calling loop, so `raw_cell` may use top-level `await`"
151
- with self._captured(stdout, stderr, display, timeout, verbose) as c:
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:
152
150
  result = await run_cell(self, raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
153
151
  return self._run_res(result, c)
154
152
 
@@ -207,18 +205,33 @@ def _out_nb(o, fmt):
207
205
  if p["output_type"]=="execute_result": p['execution_count'] = o.result.execution_count
208
206
  return res
209
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
+
210
214
  # %% ../nbs/00_shell.ipynb #242f732f
211
215
  @patch
212
- async def run(
216
+ def run(
213
217
  self:CaptureShell,
214
218
  code:str, # Python/IPython code to run
215
219
  stdout=True, # Capture stdout and save as output?
216
220
  stderr=True, # Capture stderr and save as output?
217
- timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
218
- 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
219
224
  ):
220
- "Run `code`, returning a list of all outputs in Jupyter notebook format"
221
- res = await self._run_async(code, store_history=True, 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)])
222
235
  self.result = res.result.result
223
236
  self.exc = res.exception
224
237
  return _out_nb(res, self.display_formatter)
@@ -269,11 +282,11 @@ def render_outputs(outputs, ansi_renderer=_strip, include_imgs=True, pygments=Fa
269
282
 
270
283
  # %% ../nbs/00_shell.ipynb #c6176b9e
271
284
  @patch
272
- async def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
285
+ def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False, timeout=None):
273
286
  "Run `cell`, skipping if not code, and store outputs (and the execution count) back in cell"
274
287
  if cell.cell_type!='code': return
275
288
  self._cell_idx = cell.idx_ + 1
276
- outs = await self.run(cell.source, verbose=verbose)
289
+ outs = self.run(cell.source, stdout=stdout, stderr=stderr, verbose=verbose, timeout=timeout)
277
290
  cell.outputs = _dict2obj(outs) if outs else []
278
291
  cell.execution_count = self.execution_count-1 # the count this run used: the shell has already advanced
279
292
 
@@ -308,7 +321,22 @@ def out_error(outp):
308
321
  def _false(o): return False
309
322
 
310
323
  @patch
311
- async def run_all(
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
+
338
+ @patch
339
+ def run_all(
312
340
  self:CaptureShell,
313
341
  nb, # A notebook read with `nbclient` or `read_nb`
314
342
  exc_stop:bool=False, # Stop on exceptions?
@@ -316,19 +344,24 @@ async def run_all(
316
344
  postproc:callable=_false, # Called after each cell is executed
317
345
  inject_code:str|None=None, # Code to inject into a cell
318
346
  inject_idx:int=0, # Cell to replace with `inject_code`
319
- 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
320
350
  ):
321
- "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`"
322
352
  if inject_code is not None: nb.cells[inject_idx].source = inject_code
353
+ before = asyncio.all_tasks(self.loop)
323
354
  for cell in nb.cells:
324
355
  if not preproc(cell):
325
- await self.cell(cell, verbose=verbose)
356
+ self.cell(cell, verbose=verbose, timeout=cell_timeout)
326
357
  postproc(cell)
327
- 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
328
361
 
329
362
  # %% ../nbs/00_shell.ipynb #70808010
330
363
  @patch
331
- async def execute(
364
+ def execute(
332
365
  self:CaptureShell,
333
366
  src:str|Path, # Notebook path to read from
334
367
  dest:str|None=None, # Notebook path to write to
@@ -338,15 +371,16 @@ async def execute(
338
371
  inject_code:str|None=None, # Code to inject into a cell
339
372
  inject_path:str|Path|None=None, # Path to file containing code to inject into a cell
340
373
  inject_idx:int=0, # Cell to replace with `inject_code`
341
- 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)
342
376
  ):
343
377
  "Execute notebook from `src` and save with outputs to `dest"
344
378
  nb = read_nb(src)
345
379
  self._fname = src
346
380
  self.set_path(Path(src).parent.resolve())
347
381
  if inject_path is not None: inject_code = Path(inject_path).read_text()
348
- await self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
349
- inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
382
+ self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
383
+ inject_code=inject_code, inject_idx=inject_idx, verbose=verbose, cell_timeout=cell_timeout)
350
384
  if dest: write_nb(nb, dest)
351
385
 
352
386
  # %% ../nbs/00_shell.ipynb #694161cb
@@ -368,24 +402,25 @@ from fastcore.nbio import render_text
368
402
  # %% ../nbs/00_shell.ipynb #31536fa0
369
403
  @patch
370
404
  @delegates(CaptureShell.run)
371
- async def run_text(self:CaptureShell, code, **kwargs):
405
+ def run_text(self:CaptureShell, code, **kwargs):
372
406
  "Run `code`, returning its outputs rendered as concise text: what a notebook's output area shows"
373
- return render_text(await self.run(code, **kwargs))
407
+ return render_text(self.run(code, **kwargs))
374
408
 
375
409
  # %% ../nbs/00_shell.ipynb #1227c8b1
376
410
  @call_parse
377
- async def exec_nb(
411
+ def exec_nb(
378
412
  src:str, # Notebook path to read from
379
413
  dest:str='', # Notebook path to write to
380
414
  exc_stop:bool=False, # Stop on exceptions?
381
415
  inject_code:str=None, # Code to inject into a cell
382
416
  inject_path:str=None, # Path to file containing code to inject into a cell
383
417
  inject_idx:int=0, # Cell to replace with `inject_code`
384
- 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)
385
420
  ):
386
421
  "Execute notebook from `src` and save with outputs to `dest`"
387
- await CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
388
- inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
422
+ CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
423
+ inject_path=inject_path, inject_idx=inject_idx, verbose=verbose, cell_timeout=cell_timeout)
389
424
 
390
425
  # %% ../nbs/00_shell.ipynb #c44963a0
391
426
  class SmartCompleter(IPCompleter):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.3.0
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
@@ -1,7 +1,6 @@
1
- """Nested execution: a cell driving `fastcore.nbio.run_cell` against a shell, in a loopless
2
- process (the nbdev-test environment, entered through `asyncio.run` at the boundary). Pins that
3
- inner-run assignments persist in the right namespace and errors stay structural."""
4
- import asyncio
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."""
5
4
  from IPython.core.interactiveshell import InteractiveShell
6
5
  from execnb.shell import CaptureShell
7
6
 
@@ -10,11 +9,11 @@ def test_nested_run_separate_shell():
10
9
  "Inner runs against a second shell: assignments persist in the inner ns, visible during and after the outer cell"
11
10
  k = CaptureShell(mpl_format=None)
12
11
  k.user_ns['psh'] = InteractiveShell()
13
- outs = asyncio.run(k.run(
12
+ outs = k.run(
14
13
  "from fastcore.nbio import run_cell\n"
15
14
  "r1 = await run_cell(psh, 'zz = 5', silent=True)\n"
16
15
  "r2 = await run_cell(psh, 'zz2 = zz+1', store_history=True)\n"
17
- "ok = psh.user_ns.get('zz')==5 and psh.user_ns.get('zz2')==6"))
16
+ "ok = psh.user_ns.get('zz')==5 and psh.user_ns.get('zz2')==6")
18
17
  assert not k.exc, outs
19
18
  psh = k.user_ns['psh']
20
19
  assert k.user_ns['ok'], 'inner assignments not visible inside the outer cell'
@@ -24,11 +23,11 @@ def test_nested_run_separate_shell():
24
23
  def test_nested_run_self_shell():
25
24
  "Inner runs against the outer shell itself via get_ipython(): assignments persist in its ns"
26
25
  k = CaptureShell(mpl_format=None)
27
- outs = asyncio.run(k.run(
26
+ outs = k.run(
28
27
  "from fastcore.nbio import run_cell\n"
29
28
  "await run_cell(get_ipython(), 'qq = 7', silent=True)\n"
30
29
  "await run_cell(get_ipython(), 'qq2 = qq+1', store_history=True)\n"
31
- "inner_saw = get_ipython().user_ns.get('qq2')"))
30
+ "inner_saw = get_ipython().user_ns.get('qq2')")
32
31
  assert not k.exc, outs
33
32
  assert k.user_ns.get('inner_saw')==8, 'inner runs did not see their own writes'
34
33
  assert k.user_ns.get('qq')==7 and k.user_ns.get('qq2')==8, \
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"
File without changes
File without changes
File without changes
File without changes
File without changes