execnb 0.3.0__py3-none-any.whl → 0.3.2__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 +1 -1
- execnb/_modidx.py +3 -0
- execnb/shell.py +78 -43
- {execnb-0.3.0.dist-info → execnb-0.3.2.dist-info}/METADATA +1 -1
- execnb-0.3.2.dist-info/RECORD +9 -0
- {execnb-0.3.0.dist-info → execnb-0.3.2.dist-info}/WHEEL +1 -1
- execnb-0.3.0.dist-info/RECORD +0 -9
- {execnb-0.3.0.dist-info → execnb-0.3.2.dist-info}/entry_points.txt +0 -0
- {execnb-0.3.0.dist-info → execnb-0.3.2.dist-info}/licenses/LICENSE +0 -0
- {execnb-0.3.0.dist-info → execnb-0.3.2.dist-info}/top_level.txt +0 -0
execnb/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.3.
|
|
1
|
+
__version__ = "0.3.2"
|
execnb/_modidx.py
CHANGED
|
@@ -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'),
|
execnb/shell.py
CHANGED
|
@@ -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,
|
|
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,
|
|
111
|
-
"Output capture
|
|
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,
|
|
141
|
-
"Sync captured run through IPython's own `run_cell` entry, for constructor-time setup lines
|
|
142
|
-
with self._captured(stdout, stderr, display,
|
|
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,
|
|
150
|
-
"Async `_run`: awaits the cell via `fastcore.nbio.run_cell
|
|
151
|
-
with self._captured(stdout, stderr, display,
|
|
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
|
-
|
|
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, #
|
|
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
|
|
221
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
356
|
+
self.cell(cell, verbose=verbose, timeout=cell_timeout)
|
|
326
357
|
postproc(cell)
|
|
327
|
-
if self.exc and exc_stop:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
407
|
+
return render_text(self.run(code, **kwargs))
|
|
374
408
|
|
|
375
409
|
# %% ../nbs/00_shell.ipynb #1227c8b1
|
|
376
410
|
@call_parse
|
|
377
|
-
|
|
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
|
-
|
|
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):
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
execnb/__init__.py,sha256=vNiWJ14r_cw5t_7UDqDQIVZvladKFGyHH2avsLpN7Vg,22
|
|
2
|
+
execnb/_modidx.py,sha256=MjNuUL_bi4wfGKPaqwskCCqi4at5zy9Ju2YxO5qv6L0,6165
|
|
3
|
+
execnb/shell.py,sha256=RAs7b6khhpdvRe8RdaVWqiFG6_5CGFXLs7l8whfY1E4,20088
|
|
4
|
+
execnb-0.3.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
5
|
+
execnb-0.3.2.dist-info/METADATA,sha256=zjIJtSSLwiCLjiN_gfxt_sQ69ZI8xdJt1pJAoLZ8fd8,3347
|
|
6
|
+
execnb-0.3.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
execnb-0.3.2.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
|
|
8
|
+
execnb-0.3.2.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
|
|
9
|
+
execnb-0.3.2.dist-info/RECORD,,
|
execnb-0.3.0.dist-info/RECORD
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
execnb/__init__.py,sha256=VrXpHDu3erkzwl_WXrqINBm9xWkcyUy53IQOj042dOs,22
|
|
2
|
-
execnb/_modidx.py,sha256=cEM3nAZSobNuYw4tAMq2eAdHhU4nscv_MgYyEu0vFYs,5820
|
|
3
|
-
execnb/shell.py,sha256=vvy5VJySZUVs8q2pxTwlYIQnp1Y_3FLwAWql0LQZ1rA,18236
|
|
4
|
-
execnb-0.3.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
5
|
-
execnb-0.3.0.dist-info/METADATA,sha256=HYahRVjopkpW8tvcCaEwHafpz8cUZ7_E7dYVVITS_BI,3347
|
|
6
|
-
execnb-0.3.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
7
|
-
execnb-0.3.0.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
|
|
8
|
-
execnb-0.3.0.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
|
|
9
|
-
execnb-0.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|