execnb 0.2.10__tar.gz → 0.3.0__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.
- {execnb-0.2.10/execnb.egg-info → execnb-0.3.0}/PKG-INFO +5 -7
- {execnb-0.2.10 → execnb-0.3.0}/README.md +3 -5
- execnb-0.3.0/execnb/__init__.py +1 -0
- {execnb-0.2.10 → execnb-0.3.0}/execnb/_modidx.py +1 -3
- {execnb-0.2.10 → execnb-0.3.0}/execnb/shell.py +43 -90
- {execnb-0.2.10 → execnb-0.3.0/execnb.egg-info}/PKG-INFO +5 -7
- {execnb-0.2.10 → execnb-0.3.0}/execnb.egg-info/SOURCES.txt +2 -1
- {execnb-0.2.10 → execnb-0.3.0}/execnb.egg-info/requires.txt +1 -1
- {execnb-0.2.10 → execnb-0.3.0}/pyproject.toml +1 -1
- execnb-0.3.0/tests/test_shell.py +35 -0
- execnb-0.2.10/execnb/__init__.py +0 -1
- {execnb-0.2.10 → execnb-0.3.0}/LICENSE +0 -0
- {execnb-0.2.10 → execnb-0.3.0}/MANIFEST.in +0 -0
- {execnb-0.2.10 → execnb-0.3.0}/execnb.egg-info/dependency_links.txt +0 -0
- {execnb-0.2.10 → execnb-0.3.0}/execnb.egg-info/entry_points.txt +0 -0
- {execnb-0.2.10 → execnb-0.3.0}/execnb.egg-info/top_level.txt +0 -0
- {execnb-0.2.10 → execnb-0.3.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: execnb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
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.
|
|
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
|
-
[](https://github.com/fastai/execnb/actions/workflows/test.yaml) [](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
|
-
[](https://github.com/fastai/execnb/actions/workflows/test.yaml) [](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.0"
|
|
@@ -11,7 +11,6 @@ d = { 'settings': { 'branch': 'main',
|
|
|
11
11
|
'execnb.shell.CaptureShell._run': ('shell.html#captureshell._run', 'execnb/shell.py'),
|
|
12
12
|
'execnb.shell.CaptureShell._run_async': ('shell.html#captureshell._run_async', 'execnb/shell.py'),
|
|
13
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'),
|
|
15
14
|
'execnb.shell.CaptureShell.cell': ('shell.html#captureshell.cell', 'execnb/shell.py'),
|
|
16
15
|
'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
|
|
17
16
|
'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
|
|
@@ -20,8 +19,6 @@ d = { 'settings': { 'branch': 'main',
|
|
|
20
19
|
'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
|
|
21
20
|
'execnb.shell.CaptureShell.run': ('shell.html#captureshell.run', 'execnb/shell.py'),
|
|
22
21
|
'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
22
|
'execnb.shell.CaptureShell.run_text': ('shell.html#captureshell.run_text', 'execnb/shell.py'),
|
|
26
23
|
'execnb.shell.CaptureShell.set_path': ('shell.html#captureshell.set_path', 'execnb/shell.py'),
|
|
27
24
|
'execnb.shell.CaptureShell.showsyntaxerror': ('shell.html#captureshell.showsyntaxerror', 'execnb/shell.py'),
|
|
@@ -41,6 +38,7 @@ d = { 'settings': { 'branch': 'main',
|
|
|
41
38
|
'execnb.shell._false': ('shell.html#_false', 'execnb/shell.py'),
|
|
42
39
|
'execnb.shell._format_mimedata': ('shell.html#_format_mimedata', 'execnb/shell.py'),
|
|
43
40
|
'execnb.shell._mk_out': ('shell.html#_mk_out', 'execnb/shell.py'),
|
|
41
|
+
'execnb.shell._no_stdin': ('shell.html#_no_stdin', 'execnb/shell.py'),
|
|
44
42
|
'execnb.shell._out_exc': ('shell.html#_out_exc', 'execnb/shell.py'),
|
|
45
43
|
'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
|
|
46
44
|
'execnb.shell._out_stream': ('shell.html#_out_stream', 'execnb/shell.py'),
|
|
@@ -14,7 +14,7 @@ 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
|
|
17
|
+
import multiprocessing,types,traceback,signal,builtins
|
|
18
18
|
from contextlib import contextmanager
|
|
19
19
|
try:
|
|
20
20
|
if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
|
|
@@ -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
|
|
@@ -98,90 +98,60 @@ class CaptureShell(InteractiveShell):
|
|
|
98
98
|
"Add `path` to python path, or `path.parent` if it's a file"
|
|
99
99
|
path = Path(path)
|
|
100
100
|
if path.is_file(): path = path.parent
|
|
101
|
-
self._run(f"import sys
|
|
101
|
+
self._run(f"import sys\nif '{path.as_posix()}' not in sys.path: sys.path.insert(0, '{path.as_posix()}')")
|
|
102
102
|
|
|
103
103
|
def enable_gui(self, gui=None): pass
|
|
104
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)
|
|
112
|
-
|
|
113
|
-
|
|
114
105
|
# %% ../nbs/00_shell.ipynb #6f0cac34
|
|
106
|
+
def _no_stdin(*args, **kw): raise StdinNotImplementedError('input() is not supported in a captured run')
|
|
107
|
+
|
|
115
108
|
@patch
|
|
116
109
|
@contextmanager
|
|
117
110
|
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"
|
|
111
|
+
"Output capture, stdin blocking, and optional SIGALRM timeout around one cell run"
|
|
119
112
|
if not timeout: timeout = self.timeout
|
|
113
|
+
prev_alarm = None
|
|
120
114
|
if timeout:
|
|
121
115
|
def handler(*args): raise TimeoutError()
|
|
122
|
-
signal.signal(signal.SIGALRM, handler)
|
|
116
|
+
prev_alarm = signal.signal(signal.SIGALRM, handler)
|
|
123
117
|
signal.alarm(timeout)
|
|
118
|
+
prev_input = builtins.input
|
|
119
|
+
builtins.input = _no_stdin
|
|
124
120
|
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
|
|
121
|
+
with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c: yield c
|
|
129
122
|
finally:
|
|
130
|
-
|
|
123
|
+
builtins.input = prev_input
|
|
124
|
+
if timeout:
|
|
125
|
+
signal.alarm(0)
|
|
126
|
+
signal.signal(signal.SIGALRM, prev_alarm)
|
|
131
127
|
|
|
132
128
|
# %% ../nbs/00_shell.ipynb #cdb9dc37
|
|
133
129
|
@patch
|
|
134
|
-
def _run_res(self:CaptureShell, result, c
|
|
130
|
+
def _run_res(self:CaptureShell, result, c):
|
|
135
131
|
"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
132
|
e = result.error_in_exec or result.error_before_exec
|
|
139
133
|
if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
|
|
140
134
|
e.args = (f"{e} A cell magic (%%) must start the cell; remove or move the lines above it.",)
|
|
141
|
-
return AttrDict(result=result, stdout=
|
|
142
|
-
exception=e, quiet=semic)
|
|
135
|
+
return AttrDict(result=result, stdout=c.stdout, stderr=c.stderr, display_objects=c.outputs, exception=e)
|
|
143
136
|
|
|
144
137
|
# %% ../nbs/00_shell.ipynb #5bc0e776
|
|
145
138
|
@patch
|
|
146
139
|
def _run(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
|
|
147
140
|
stdout=True, stderr=True, display=True, timeout=None, verbose=False):
|
|
148
|
-
"
|
|
141
|
+
"Sync captured run through IPython's own `run_cell` entry, for constructor-time setup lines that run before any loop exists"
|
|
149
142
|
with self._captured(stdout, stderr, display, timeout, verbose) as c:
|
|
150
143
|
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
|
|
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
|
|
144
|
+
return self._run_res(result, c)
|
|
176
145
|
|
|
177
146
|
# %% ../nbs/00_shell.ipynb #1483d0f2
|
|
178
147
|
@patch
|
|
179
148
|
async def _run_async(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
|
|
180
149
|
stdout=True, stderr=True, display=True, timeout=None, verbose=False):
|
|
181
|
-
"Async `_run`: awaits the cell on the calling
|
|
150
|
+
"Async `_run`: awaits the cell via `fastcore.nbio.run_cell` on the calling loop, so `raw_cell` may use top-level `await`"
|
|
182
151
|
with self._captured(stdout, stderr, display, timeout, verbose) as c:
|
|
183
|
-
result = await self
|
|
184
|
-
return self._run_res(result, c
|
|
152
|
+
result = await run_cell(self, raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
|
|
153
|
+
return self._run_res(result, c)
|
|
154
|
+
|
|
185
155
|
|
|
186
156
|
# %% ../nbs/00_shell.ipynb #a05e1b43
|
|
187
157
|
@patch
|
|
@@ -210,11 +180,8 @@ def format_exc(e):
|
|
|
210
180
|
class NbResult(list): pass
|
|
211
181
|
|
|
212
182
|
# %% ../nbs/00_shell.ipynb #26bf9161
|
|
213
|
-
def _out_stream(text, name): return
|
|
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))
|
|
183
|
+
def _out_stream(text, name): return mk_stream(name, text.splitlines(True))
|
|
184
|
+
def _out_exc(e): return mk_error(format_exc(e), ename=type(e).__name__, evalue=str(e))
|
|
218
185
|
|
|
219
186
|
def _format_mimedata(k, v):
|
|
220
187
|
"Format mime-type keyed data consistently with Jupyter"
|
|
@@ -235,15 +202,14 @@ def _out_nb(o, fmt):
|
|
|
235
202
|
if o.exception: res.append(_out_exc(o.exception))
|
|
236
203
|
res.result = o.result.result
|
|
237
204
|
for x in o.display_objects: res.append(_mk_out(x.data, x.metadata))
|
|
238
|
-
if res.result is not None
|
|
239
|
-
if 'execution_count' not in o: o['execution_count']=None
|
|
205
|
+
if res.result is not None: res.append(_mk_out(*fmt.format(res.result), 'execute_result'))
|
|
240
206
|
for p in res:
|
|
241
|
-
if p["output_type"]=="execute_result": p['execution_count'] = o
|
|
207
|
+
if p["output_type"]=="execute_result": p['execution_count'] = o.result.execution_count
|
|
242
208
|
return res
|
|
243
209
|
|
|
244
210
|
# %% ../nbs/00_shell.ipynb #242f732f
|
|
245
211
|
@patch
|
|
246
|
-
def run(
|
|
212
|
+
async def run(
|
|
247
213
|
self:CaptureShell,
|
|
248
214
|
code:str, # Python/IPython code to run
|
|
249
215
|
stdout=True, # Capture stdout and save as output?
|
|
@@ -252,23 +218,7 @@ def run(
|
|
|
252
218
|
verbose:bool=False # Show stdout/stderr during execution
|
|
253
219
|
):
|
|
254
220
|
"Run `code`, returning a list of all outputs in Jupyter notebook format"
|
|
255
|
-
res = self.
|
|
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)
|
|
221
|
+
res = await self._run_async(code, store_history=True, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
|
|
272
222
|
self.result = res.result.result
|
|
273
223
|
self.exc = res.exception
|
|
274
224
|
return _out_nb(res, self.display_formatter)
|
|
@@ -319,12 +269,14 @@ def render_outputs(outputs, ansi_renderer=_strip, include_imgs=True, pygments=Fa
|
|
|
319
269
|
|
|
320
270
|
# %% ../nbs/00_shell.ipynb #c6176b9e
|
|
321
271
|
@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"
|
|
272
|
+
async def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
|
|
273
|
+
"Run `cell`, skipping if not code, and store outputs (and the execution count) back in cell"
|
|
324
274
|
if cell.cell_type!='code': return
|
|
325
275
|
self._cell_idx = cell.idx_ + 1
|
|
326
|
-
outs = self.run(cell.source, verbose=verbose)
|
|
276
|
+
outs = await self.run(cell.source, verbose=verbose)
|
|
327
277
|
cell.outputs = _dict2obj(outs) if outs else []
|
|
278
|
+
cell.execution_count = self.execution_count-1 # the count this run used: the shell has already advanced
|
|
279
|
+
|
|
328
280
|
|
|
329
281
|
# %% ../nbs/00_shell.ipynb #008c0cef
|
|
330
282
|
def find_output(
|
|
@@ -356,7 +308,7 @@ def out_error(outp):
|
|
|
356
308
|
def _false(o): return False
|
|
357
309
|
|
|
358
310
|
@patch
|
|
359
|
-
def run_all(
|
|
311
|
+
async def run_all(
|
|
360
312
|
self:CaptureShell,
|
|
361
313
|
nb, # A notebook read with `nbclient` or `read_nb`
|
|
362
314
|
exc_stop:bool=False, # Stop on exceptions?
|
|
@@ -370,13 +322,13 @@ def run_all(
|
|
|
370
322
|
if inject_code is not None: nb.cells[inject_idx].source = inject_code
|
|
371
323
|
for cell in nb.cells:
|
|
372
324
|
if not preproc(cell):
|
|
373
|
-
self.cell(cell, verbose=verbose)
|
|
325
|
+
await self.cell(cell, verbose=verbose)
|
|
374
326
|
postproc(cell)
|
|
375
327
|
if self.exc and exc_stop: raise self.exc from None
|
|
376
328
|
|
|
377
329
|
# %% ../nbs/00_shell.ipynb #70808010
|
|
378
330
|
@patch
|
|
379
|
-
def execute(
|
|
331
|
+
async def execute(
|
|
380
332
|
self:CaptureShell,
|
|
381
333
|
src:str|Path, # Notebook path to read from
|
|
382
334
|
dest:str|None=None, # Notebook path to write to
|
|
@@ -393,7 +345,7 @@ def execute(
|
|
|
393
345
|
self._fname = src
|
|
394
346
|
self.set_path(Path(src).parent.resolve())
|
|
395
347
|
if inject_path is not None: inject_code = Path(inject_path).read_text()
|
|
396
|
-
self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
|
|
348
|
+
await self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
|
|
397
349
|
inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
|
|
398
350
|
if dest: write_nb(nb, dest)
|
|
399
351
|
|
|
@@ -402,6 +354,7 @@ def execute(
|
|
|
402
354
|
def prettytb(self:CaptureShell,
|
|
403
355
|
fname:str|Path=None): # filename to print alongside the traceback
|
|
404
356
|
"Show a pretty traceback for notebooks, optionally printing `fname`."
|
|
357
|
+
if self.exc is None: return ""
|
|
405
358
|
fname = fname if fname else self._fname
|
|
406
359
|
_fence = '='*75
|
|
407
360
|
cell_intro_str = f"While Executing Cell #{self._cell_idx}:" if self._cell_idx else "While Executing:"
|
|
@@ -415,13 +368,13 @@ from fastcore.nbio import render_text
|
|
|
415
368
|
# %% ../nbs/00_shell.ipynb #31536fa0
|
|
416
369
|
@patch
|
|
417
370
|
@delegates(CaptureShell.run)
|
|
418
|
-
def run_text(self:CaptureShell, code, **kwargs):
|
|
371
|
+
async def run_text(self:CaptureShell, code, **kwargs):
|
|
419
372
|
"Run `code`, returning its outputs rendered as concise text: what a notebook's output area shows"
|
|
420
|
-
return render_text(self.run(code, **kwargs))
|
|
373
|
+
return render_text(await self.run(code, **kwargs))
|
|
421
374
|
|
|
422
375
|
# %% ../nbs/00_shell.ipynb #1227c8b1
|
|
423
376
|
@call_parse
|
|
424
|
-
def exec_nb(
|
|
377
|
+
async def exec_nb(
|
|
425
378
|
src:str, # Notebook path to read from
|
|
426
379
|
dest:str='', # Notebook path to write to
|
|
427
380
|
exc_stop:bool=False, # Stop on exceptions?
|
|
@@ -431,7 +384,7 @@ def exec_nb(
|
|
|
431
384
|
verbose:bool=False # Show stdout/stderr during execution
|
|
432
385
|
):
|
|
433
386
|
"Execute notebook from `src` and save with outputs to `dest`"
|
|
434
|
-
CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
|
|
387
|
+
await CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
|
|
435
388
|
inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
|
|
436
389
|
|
|
437
390
|
# %% ../nbs/00_shell.ipynb #c44963a0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: execnb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
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.
|
|
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
|
-
[](https://github.com/fastai/execnb/actions/workflows/test.yaml) [](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
|
```
|
|
@@ -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.
|
|
15
|
+
dependencies = ['fastcore>=2.2.5', 'ipython']
|
|
16
16
|
|
|
17
17
|
[project.urls]
|
|
18
18
|
Repository = "https://github.com/AnswerDotAI/execnb/"
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
|
5
|
+
from IPython.core.interactiveshell import InteractiveShell
|
|
6
|
+
from execnb.shell import CaptureShell
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_nested_run_separate_shell():
|
|
10
|
+
"Inner runs against a second shell: assignments persist in the inner ns, visible during and after the outer cell"
|
|
11
|
+
k = CaptureShell(mpl_format=None)
|
|
12
|
+
k.user_ns['psh'] = InteractiveShell()
|
|
13
|
+
outs = asyncio.run(k.run(
|
|
14
|
+
"from fastcore.nbio import run_cell\n"
|
|
15
|
+
"r1 = await run_cell(psh, 'zz = 5', silent=True)\n"
|
|
16
|
+
"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"))
|
|
18
|
+
assert not k.exc, outs
|
|
19
|
+
psh = k.user_ns['psh']
|
|
20
|
+
assert k.user_ns['ok'], 'inner assignments not visible inside the outer cell'
|
|
21
|
+
assert psh.user_ns.get('zz')==5 and psh.user_ns.get('zz2')==6, 'inner assignments lost after the outer cell'
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_nested_run_self_shell():
|
|
25
|
+
"Inner runs against the outer shell itself via get_ipython(): assignments persist in its ns"
|
|
26
|
+
k = CaptureShell(mpl_format=None)
|
|
27
|
+
outs = asyncio.run(k.run(
|
|
28
|
+
"from fastcore.nbio import run_cell\n"
|
|
29
|
+
"await run_cell(get_ipython(), 'qq = 7', silent=True)\n"
|
|
30
|
+
"await run_cell(get_ipython(), 'qq2 = qq+1', store_history=True)\n"
|
|
31
|
+
"inner_saw = get_ipython().user_ns.get('qq2')"))
|
|
32
|
+
assert not k.exc, outs
|
|
33
|
+
assert k.user_ns.get('inner_saw')==8, 'inner runs did not see their own writes'
|
|
34
|
+
assert k.user_ns.get('qq')==7 and k.user_ns.get('qq2')==8, \
|
|
35
|
+
f"assignments lost after outer cell: qq={k.user_ns.get('qq')} qq2={k.user_ns.get('qq2')}"
|
execnb-0.2.10/execnb/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.2.10"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|