execnb 0.2.9__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.9/execnb.egg-info → execnb-0.3.0}/PKG-INFO +5 -7
- {execnb-0.2.9 → execnb-0.3.0}/README.md +3 -5
- execnb-0.3.0/execnb/__init__.py +1 -0
- {execnb-0.2.9 → execnb-0.3.0}/execnb/_modidx.py +8 -8
- {execnb-0.2.9 → execnb-0.3.0}/execnb/shell.py +85 -121
- {execnb-0.2.9 → execnb-0.3.0/execnb.egg-info}/PKG-INFO +5 -7
- {execnb-0.2.9 → execnb-0.3.0}/execnb.egg-info/SOURCES.txt +2 -1
- {execnb-0.2.9 → execnb-0.3.0}/execnb.egg-info/requires.txt +1 -1
- {execnb-0.2.9 → execnb-0.3.0}/pyproject.toml +1 -1
- execnb-0.3.0/tests/test_shell.py +35 -0
- execnb-0.2.9/execnb/__init__.py +0 -1
- {execnb-0.2.9 → execnb-0.3.0}/LICENSE +0 -0
- {execnb-0.2.9 → execnb-0.3.0}/MANIFEST.in +0 -0
- {execnb-0.2.9 → execnb-0.3.0}/execnb.egg-info/dependency_links.txt +0 -0
- {execnb-0.2.9 → execnb-0.3.0}/execnb.egg-info/entry_points.txt +0 -0
- {execnb-0.2.9 → execnb-0.3.0}/execnb.egg-info/top_level.txt +0 -0
- {execnb-0.2.9 → 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"
|
|
@@ -7,20 +7,22 @@ d = { 'settings': { 'branch': 'main',
|
|
|
7
7
|
'lib_path': 'execnb'},
|
|
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
|
+
'execnb.shell.CaptureShell._captured': ('shell.html#captureshell._captured', 'execnb/shell.py'),
|
|
10
11
|
'execnb.shell.CaptureShell._run': ('shell.html#captureshell._run', 'execnb/shell.py'),
|
|
12
|
+
'execnb.shell.CaptureShell._run_async': ('shell.html#captureshell._run_async', 'execnb/shell.py'),
|
|
13
|
+
'execnb.shell.CaptureShell._run_res': ('shell.html#captureshell._run_res', 'execnb/shell.py'),
|
|
11
14
|
'execnb.shell.CaptureShell.cell': ('shell.html#captureshell.cell', 'execnb/shell.py'),
|
|
12
15
|
'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
|
|
13
16
|
'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
|
|
14
17
|
'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
|
|
15
18
|
'execnb.shell.CaptureShell.load_profile': ('shell.html#captureshell.load_profile', 'execnb/shell.py'),
|
|
16
|
-
'execnb.shell.CaptureShell.nbopen': ('shell.html#captureshell.nbopen', 'execnb/shell.py'),
|
|
17
|
-
'execnb.shell.CaptureShell.nbrun': ('shell.html#captureshell.nbrun', 'execnb/shell.py'),
|
|
18
19
|
'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
|
|
19
20
|
'execnb.shell.CaptureShell.run': ('shell.html#captureshell.run', 'execnb/shell.py'),
|
|
20
21
|
'execnb.shell.CaptureShell.run_all': ('shell.html#captureshell.run_all', 'execnb/shell.py'),
|
|
21
|
-
'execnb.shell.CaptureShell.
|
|
22
|
-
'execnb.shell.CaptureShell.run_cell': ('shell.html#captureshell.run_cell', 'execnb/shell.py'),
|
|
22
|
+
'execnb.shell.CaptureShell.run_text': ('shell.html#captureshell.run_text', 'execnb/shell.py'),
|
|
23
23
|
'execnb.shell.CaptureShell.set_path': ('shell.html#captureshell.set_path', 'execnb/shell.py'),
|
|
24
|
+
'execnb.shell.CaptureShell.showsyntaxerror': ('shell.html#captureshell.showsyntaxerror', 'execnb/shell.py'),
|
|
25
|
+
'execnb.shell.CaptureShell.showtraceback': ('shell.html#captureshell.showtraceback', 'execnb/shell.py'),
|
|
24
26
|
'execnb.shell.ExecutionInfo.__repr__': ('shell.html#executioninfo.__repr__', 'execnb/shell.py'),
|
|
25
27
|
'execnb.shell.ExecutionResult.__repr__': ('shell.html#executionresult.__repr__', 'execnb/shell.py'),
|
|
26
28
|
'execnb.shell.NbResult': ('shell.html#nbresult', 'execnb/shell.py'),
|
|
@@ -35,9 +37,8 @@ d = { 'settings': { 'branch': 'main',
|
|
|
35
37
|
'execnb/shell.py'),
|
|
36
38
|
'execnb.shell._false': ('shell.html#_false', 'execnb/shell.py'),
|
|
37
39
|
'execnb.shell._format_mimedata': ('shell.html#_format_mimedata', 'execnb/shell.py'),
|
|
38
|
-
'execnb.shell._is_exported': ('shell.html#_is_exported', 'execnb/shell.py'),
|
|
39
|
-
'execnb.shell._is_noeval': ('shell.html#_is_noeval', 'execnb/shell.py'),
|
|
40
40
|
'execnb.shell._mk_out': ('shell.html#_mk_out', 'execnb/shell.py'),
|
|
41
|
+
'execnb.shell._no_stdin': ('shell.html#_no_stdin', 'execnb/shell.py'),
|
|
41
42
|
'execnb.shell._out_exc': ('shell.html#_out_exc', 'execnb/shell.py'),
|
|
42
43
|
'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
|
|
43
44
|
'execnb.shell._out_stream': ('shell.html#_out_stream', 'execnb/shell.py'),
|
|
@@ -51,5 +52,4 @@ d = { 'settings': { 'branch': 'main',
|
|
|
51
52
|
'execnb.shell.out_error': ('shell.html#out_error', 'execnb/shell.py'),
|
|
52
53
|
'execnb.shell.out_exec': ('shell.html#out_exec', 'execnb/shell.py'),
|
|
53
54
|
'execnb.shell.out_stream': ('shell.html#out_stream', 'execnb/shell.py'),
|
|
54
|
-
'execnb.shell.render_outputs': ('shell.html#render_outputs', 'execnb/shell.py')
|
|
55
|
-
'execnb.shell.select_cells': ('shell.html#select_cells', 'execnb/shell.py')}}}
|
|
55
|
+
'execnb.shell.render_outputs': ('shell.html#render_outputs', 'execnb/shell.py')}}}
|
|
@@ -6,14 +6,16 @@ Docs: https://AnswerDotAI.github.io/execnb/shell.html.md"""
|
|
|
6
6
|
|
|
7
7
|
# %% auto #0
|
|
8
8
|
__all__ = ['leading_comment_lines', 'CaptureShell', 'format_exc', 'NbResult', 'render_outputs', 'find_output', 'out_exec',
|
|
9
|
-
'out_stream', 'out_error', '
|
|
9
|
+
'out_stream', 'out_error', 'exec_nb', 'SmartCompleter']
|
|
10
10
|
|
|
11
11
|
# %% ../nbs/00_shell.ipynb #535003cf
|
|
12
12
|
from fastcore.utils import *
|
|
13
|
+
from fastcore.meta import delegates
|
|
13
14
|
from fastcore.script import call_parse
|
|
14
15
|
from fastcore.ansi import strip_ansi
|
|
15
16
|
|
|
16
|
-
import multiprocessing,types,traceback,signal
|
|
17
|
+
import multiprocessing,types,traceback,signal,builtins
|
|
18
|
+
from contextlib import contextmanager
|
|
17
19
|
try:
|
|
18
20
|
if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
|
|
19
21
|
except RuntimeError: pass # if re-running cell
|
|
@@ -22,7 +24,7 @@ from traitlets.config import Config
|
|
|
22
24
|
from traitlets.config.loader import PyFileConfigLoader
|
|
23
25
|
from IPython.paths import get_ipython_dir
|
|
24
26
|
from IPython.core.interactiveshell import InteractiveShell, ExecutionInfo, ExecutionResult
|
|
25
|
-
from IPython.core.error import UsageError
|
|
27
|
+
from IPython.core.error import UsageError, StdinNotImplementedError
|
|
26
28
|
from IPython.core.displayhook import DisplayHook
|
|
27
29
|
from IPython.utils.capture import capture_output
|
|
28
30
|
from IPython.core.completer import IPCompleter,provisionalcompleter
|
|
@@ -70,6 +72,7 @@ def leading_comment_lines(lines):
|
|
|
70
72
|
# %% ../nbs/00_shell.ipynb #e3fb2bee
|
|
71
73
|
class CaptureShell(InteractiveShell):
|
|
72
74
|
displayhook_class = _CustDisplayHook
|
|
75
|
+
_nested = False
|
|
73
76
|
|
|
74
77
|
def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None, profile:bool=False):
|
|
75
78
|
cfg = _profile_cfg()[0] if profile else Config()
|
|
@@ -78,7 +81,7 @@ class CaptureShell(InteractiveShell):
|
|
|
78
81
|
self.input_transformers_cleanup.append(leading_comment_lines)
|
|
79
82
|
self.history_manager.enabled = history
|
|
80
83
|
self.timeout = timeout
|
|
81
|
-
self.result,self.exc,self._cell_idx,self._fname
|
|
84
|
+
self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
|
|
82
85
|
if path: self.set_path(path)
|
|
83
86
|
self.display_formatter.active = True
|
|
84
87
|
if not in_notebook(): InteractiveShell._instance = self
|
|
@@ -91,44 +94,63 @@ class CaptureShell(InteractiveShell):
|
|
|
91
94
|
self._run(f"set_matplotlib_formats('{mpl_format}')")
|
|
92
95
|
if profile: self.load_profile()
|
|
93
96
|
|
|
94
|
-
def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
|
|
95
|
-
stdout=True, stderr=True, display=True, timeout=None, verbose=False):
|
|
96
|
-
"Captured execution: run `raw_cell` with output capture and optional timeout, returning an `AttrDict`"
|
|
97
|
-
# TODO what if there's a comment?
|
|
98
|
-
semic = raw_cell.rstrip().endswith(';') and not raw_cell.lstrip().startswith('%%')
|
|
99
|
-
if not timeout: timeout = self.timeout
|
|
100
|
-
if timeout:
|
|
101
|
-
def handler(*args): raise TimeoutError()
|
|
102
|
-
signal.signal(signal.SIGALRM, handler)
|
|
103
|
-
signal.alarm(timeout)
|
|
104
|
-
try:
|
|
105
|
-
with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
|
|
106
|
-
old,self._nested = self._nested,True
|
|
107
|
-
try: result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
|
|
108
|
-
finally: self._nested = old
|
|
109
|
-
finally:
|
|
110
|
-
if timeout: signal.alarm(0)
|
|
111
|
-
e = result.error_in_exec or result.error_before_exec
|
|
112
|
-
if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
|
|
113
|
-
e.args = (f"{e} A cell magic (%%) must start the cell; remove or move the lines above it.",)
|
|
114
|
-
return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr, display_objects=c.outputs,
|
|
115
|
-
exception=e, quiet=semic)
|
|
116
|
-
|
|
117
97
|
def set_path(self, path):
|
|
118
98
|
"Add `path` to python path, or `path.parent` if it's a file"
|
|
119
99
|
path = Path(path)
|
|
120
100
|
if path.is_file(): path = path.parent
|
|
121
|
-
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()}')")
|
|
122
102
|
|
|
123
103
|
def enable_gui(self, gui=None): pass
|
|
124
104
|
|
|
125
|
-
# %% ../nbs/00_shell.ipynb #
|
|
105
|
+
# %% ../nbs/00_shell.ipynb #6f0cac34
|
|
106
|
+
def _no_stdin(*args, **kw): raise StdinNotImplementedError('input() is not supported in a captured run')
|
|
107
|
+
|
|
108
|
+
@patch
|
|
109
|
+
@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
|
+
prev_input = builtins.input
|
|
119
|
+
builtins.input = _no_stdin
|
|
120
|
+
try:
|
|
121
|
+
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)
|
|
127
|
+
|
|
128
|
+
# %% ../nbs/00_shell.ipynb #cdb9dc37
|
|
129
|
+
@patch
|
|
130
|
+
def _run_res(self:CaptureShell, result, c):
|
|
131
|
+
"Package a cell `result` and its captured output `c` as the `AttrDict` rendering uses"
|
|
132
|
+
e = result.error_in_exec or result.error_before_exec
|
|
133
|
+
if isinstance(e, UsageError) and str(e).startswith('Line magic function `%%'):
|
|
134
|
+
e.args = (f"{e} A cell magic (%%) must start the cell; remove or move the lines above it.",)
|
|
135
|
+
return AttrDict(result=result, stdout=c.stdout, stderr=c.stderr, display_objects=c.outputs, exception=e)
|
|
136
|
+
|
|
137
|
+
# %% ../nbs/00_shell.ipynb #5bc0e776
|
|
138
|
+
@patch
|
|
139
|
+
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:
|
|
143
|
+
result = super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
|
|
144
|
+
return self._run_res(result, c)
|
|
145
|
+
|
|
146
|
+
# %% ../nbs/00_shell.ipynb #1483d0f2
|
|
126
147
|
@patch
|
|
127
|
-
def
|
|
148
|
+
async def _run_async(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
|
|
128
149
|
stdout=True, stderr=True, display=True, timeout=None, verbose=False):
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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:
|
|
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)
|
|
132
154
|
|
|
133
155
|
|
|
134
156
|
# %% ../nbs/00_shell.ipynb #a05e1b43
|
|
@@ -158,11 +180,8 @@ def format_exc(e):
|
|
|
158
180
|
class NbResult(list): pass
|
|
159
181
|
|
|
160
182
|
# %% ../nbs/00_shell.ipynb #26bf9161
|
|
161
|
-
def _out_stream(text, name): return
|
|
162
|
-
def _out_exc(e):
|
|
163
|
-
ename = type(e).__name__
|
|
164
|
-
tb = traceback.extract_tb(e.__traceback__)#.format()
|
|
165
|
-
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))
|
|
166
185
|
|
|
167
186
|
def _format_mimedata(k, v):
|
|
168
187
|
"Format mime-type keyed data consistently with Jupyter"
|
|
@@ -183,15 +202,14 @@ def _out_nb(o, fmt):
|
|
|
183
202
|
if o.exception: res.append(_out_exc(o.exception))
|
|
184
203
|
res.result = o.result.result
|
|
185
204
|
for x in o.display_objects: res.append(_mk_out(x.data, x.metadata))
|
|
186
|
-
if res.result is not None
|
|
187
|
-
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'))
|
|
188
206
|
for p in res:
|
|
189
|
-
if p["output_type"]=="execute_result": p['execution_count'] = o
|
|
207
|
+
if p["output_type"]=="execute_result": p['execution_count'] = o.result.execution_count
|
|
190
208
|
return res
|
|
191
209
|
|
|
192
210
|
# %% ../nbs/00_shell.ipynb #242f732f
|
|
193
211
|
@patch
|
|
194
|
-
def run(
|
|
212
|
+
async def run(
|
|
195
213
|
self:CaptureShell,
|
|
196
214
|
code:str, # Python/IPython code to run
|
|
197
215
|
stdout=True, # Capture stdout and save as output?
|
|
@@ -200,22 +218,19 @@ def run(
|
|
|
200
218
|
verbose:bool=False # Show stdout/stderr during execution
|
|
201
219
|
):
|
|
202
220
|
"Run `code`, returning a list of all outputs in Jupyter notebook format"
|
|
203
|
-
res = self.
|
|
221
|
+
res = await self._run_async(code, store_history=True, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
|
|
204
222
|
self.result = res.result.result
|
|
205
223
|
self.exc = res.exception
|
|
206
224
|
return _out_nb(res, self.display_formatter)
|
|
207
225
|
|
|
208
|
-
# %% ../nbs/00_shell.ipynb #
|
|
226
|
+
# %% ../nbs/00_shell.ipynb #16013a92
|
|
209
227
|
@patch
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
verbose:bool=False # Show stdout/stderr during execution
|
|
217
|
-
):
|
|
218
|
-
return self.run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
|
|
228
|
+
def showtraceback(self:CaptureShell, *args, **kwargs):
|
|
229
|
+
"A captured run reports its exception structurally; IPython's printed traceback would be a colored duplicate in the stream"
|
|
230
|
+
|
|
231
|
+
@patch
|
|
232
|
+
def showsyntaxerror(self:CaptureShell, *args, **kwargs):
|
|
233
|
+
"Like `showtraceback`"
|
|
219
234
|
|
|
220
235
|
# %% ../nbs/00_shell.ipynb #f698a432
|
|
221
236
|
def _pre(s, xtra=''): return f"<pre {xtra}><code>{escape(s)}</code></pre>"
|
|
@@ -254,12 +269,14 @@ def render_outputs(outputs, ansi_renderer=_strip, include_imgs=True, pygments=Fa
|
|
|
254
269
|
|
|
255
270
|
# %% ../nbs/00_shell.ipynb #c6176b9e
|
|
256
271
|
@patch
|
|
257
|
-
def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
|
|
258
|
-
"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"
|
|
259
274
|
if cell.cell_type!='code': return
|
|
260
275
|
self._cell_idx = cell.idx_ + 1
|
|
261
|
-
outs = self.run(cell.source, verbose=verbose)
|
|
276
|
+
outs = await self.run(cell.source, verbose=verbose)
|
|
262
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
|
+
|
|
263
280
|
|
|
264
281
|
# %% ../nbs/00_shell.ipynb #008c0cef
|
|
265
282
|
def find_output(
|
|
@@ -291,7 +308,7 @@ def out_error(outp):
|
|
|
291
308
|
def _false(o): return False
|
|
292
309
|
|
|
293
310
|
@patch
|
|
294
|
-
def run_all(
|
|
311
|
+
async def run_all(
|
|
295
312
|
self:CaptureShell,
|
|
296
313
|
nb, # A notebook read with `nbclient` or `read_nb`
|
|
297
314
|
exc_stop:bool=False, # Stop on exceptions?
|
|
@@ -305,13 +322,13 @@ def run_all(
|
|
|
305
322
|
if inject_code is not None: nb.cells[inject_idx].source = inject_code
|
|
306
323
|
for cell in nb.cells:
|
|
307
324
|
if not preproc(cell):
|
|
308
|
-
self.cell(cell, verbose=verbose)
|
|
325
|
+
await self.cell(cell, verbose=verbose)
|
|
309
326
|
postproc(cell)
|
|
310
327
|
if self.exc and exc_stop: raise self.exc from None
|
|
311
328
|
|
|
312
329
|
# %% ../nbs/00_shell.ipynb #70808010
|
|
313
330
|
@patch
|
|
314
|
-
def execute(
|
|
331
|
+
async def execute(
|
|
315
332
|
self:CaptureShell,
|
|
316
333
|
src:str|Path, # Notebook path to read from
|
|
317
334
|
dest:str|None=None, # Notebook path to write to
|
|
@@ -328,7 +345,7 @@ def execute(
|
|
|
328
345
|
self._fname = src
|
|
329
346
|
self.set_path(Path(src).parent.resolve())
|
|
330
347
|
if inject_path is not None: inject_code = Path(inject_path).read_text()
|
|
331
|
-
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,
|
|
332
349
|
inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
|
|
333
350
|
if dest: write_nb(nb, dest)
|
|
334
351
|
|
|
@@ -337,6 +354,7 @@ def execute(
|
|
|
337
354
|
def prettytb(self:CaptureShell,
|
|
338
355
|
fname:str|Path=None): # filename to print alongside the traceback
|
|
339
356
|
"Show a pretty traceback for notebooks, optionally printing `fname`."
|
|
357
|
+
if self.exc is None: return ""
|
|
340
358
|
fname = fname if fname else self._fname
|
|
341
359
|
_fence = '='*75
|
|
342
360
|
cell_intro_str = f"While Executing Cell #{self._cell_idx}:" if self._cell_idx else "While Executing:"
|
|
@@ -344,73 +362,19 @@ def prettytb(self:CaptureShell,
|
|
|
344
362
|
fname_str = f' in {fname}' if fname else ''
|
|
345
363
|
return f"{type(self.exc).__name__}{fname_str}:\n{_fence}\n{cell_str}\n"
|
|
346
364
|
|
|
347
|
-
# %% ../nbs/00_shell.ipynb #de6bd9f6
|
|
348
|
-
def _is_exported(cell): return cell.has_directive('export') or cell.has_directive('exports')
|
|
349
|
-
def _is_noeval(cell):
|
|
350
|
-
return 'nbdev_export'+'(' in cell.source or (cell.directive('eval') or '').lower()=='false'
|
|
351
|
-
|
|
352
|
-
def select_cells(
|
|
353
|
-
nb, # A notebook read with `read_nb`
|
|
354
|
-
msgid:str=None, # Cell id, or unique prefix, to match
|
|
355
|
-
above:bool=False, # Include the matched cell and all cells above it?
|
|
356
|
-
below:bool=False, # Include the matched cell and all cells below it?
|
|
357
|
-
all:bool=False, # Include all code cells (ignores `msgid`)?
|
|
358
|
-
exported:bool=False, # Only cells with `#| export` or `#| exports`?
|
|
359
|
-
skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
|
|
360
|
-
):
|
|
361
|
-
"Select code cells from `nb` by cell id or unique prefix"
|
|
362
|
-
cells = [o for o in nb.cells if o.cell_type=='code']
|
|
363
|
-
if not all:
|
|
364
|
-
if not msgid: raise ValueError('`msgid` required unless `all=True`')
|
|
365
|
-
idxs = [i for i,o in enumerate(cells) if str(o.id).startswith(msgid)]
|
|
366
|
-
if not idxs: raise ValueError(f'No code cell id starting with {msgid!r}')
|
|
367
|
-
if len(idxs)>1: raise ValueError(f'Multiple code cell ids start with {msgid!r}: {", ".join(str(cells[i].id) for i in idxs)}')
|
|
368
|
-
idx = idxs[0]
|
|
369
|
-
if above: cells = cells[:idx+1]
|
|
370
|
-
elif below: cells = cells[idx:]
|
|
371
|
-
else: cells = [cells[idx]]
|
|
372
|
-
if exported: cells = [o for o in cells if _is_exported(o)]
|
|
373
|
-
if skip_noeval: cells = [o for o in cells if not _is_noeval(o)]
|
|
374
|
-
return cells
|
|
375
|
-
|
|
376
365
|
# %% ../nbs/00_shell.ipynb #9c16e245
|
|
377
366
|
from fastcore.nbio import render_text
|
|
378
367
|
|
|
379
|
-
# %% ../nbs/00_shell.ipynb #
|
|
380
|
-
@patch
|
|
381
|
-
def nbopen(self:CaptureShell, fname:str|Path):
|
|
382
|
-
"Set the default notebook for `nbrun`"
|
|
383
|
-
fname = Path(fname)
|
|
384
|
-
if not fname.exists(): raise FileNotFoundError(fname)
|
|
385
|
-
self._nbrun_fname = fname
|
|
386
|
-
|
|
368
|
+
# %% ../nbs/00_shell.ipynb #31536fa0
|
|
387
369
|
@patch
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
above:bool=False, # Also run all cells above the match?
|
|
393
|
-
below:bool=False, # Also run all cells below the match?
|
|
394
|
-
all:bool=False, # Run all code cells?
|
|
395
|
-
exported:bool=False, # Only cells with `#| export` or `#| exports`?
|
|
396
|
-
skip_noeval:bool=False, # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
|
|
397
|
-
stop_on_error:bool=True, # Stop after the first cell whose run errors?
|
|
398
|
-
):
|
|
399
|
-
"Run cell(s) from a notebook by id prefix, printing rendered outputs"
|
|
400
|
-
fname = ifnone(fname, getattr(self,'_nbrun_fname',None))
|
|
401
|
-
if not fname: raise ValueError('No `fname` passed and no notebook opened with `nbopen`')
|
|
402
|
-
self.nbopen(fname)
|
|
403
|
-
nb = read_nb(fname)
|
|
404
|
-
if all or not msgids: msgids = (None,)
|
|
405
|
-
for msgid in msgids:
|
|
406
|
-
for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
|
|
407
|
-
outs = self.run(cell.source)
|
|
408
|
-
if res := render_text(outs): print(f'--- {cell.id} ---\n{res}')
|
|
409
|
-
if stop_on_error and any(o.get('output_type')=='error' for o in outs): return
|
|
370
|
+
@delegates(CaptureShell.run)
|
|
371
|
+
async def run_text(self:CaptureShell, code, **kwargs):
|
|
372
|
+
"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))
|
|
410
374
|
|
|
411
375
|
# %% ../nbs/00_shell.ipynb #1227c8b1
|
|
412
376
|
@call_parse
|
|
413
|
-
def exec_nb(
|
|
377
|
+
async def exec_nb(
|
|
414
378
|
src:str, # Notebook path to read from
|
|
415
379
|
dest:str='', # Notebook path to write to
|
|
416
380
|
exc_stop:bool=False, # Stop on exceptions?
|
|
@@ -420,7 +384,7 @@ def exec_nb(
|
|
|
420
384
|
verbose:bool=False # Show stdout/stderr during execution
|
|
421
385
|
):
|
|
422
386
|
"Execute notebook from `src` and save with outputs to `dest`"
|
|
423
|
-
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,
|
|
424
388
|
inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
|
|
425
389
|
|
|
426
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.9/execnb/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.2.9"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|