execnb 0.2.6__py3-none-any.whl → 0.2.8__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 CHANGED
@@ -1 +1 @@
1
- __version__ = "0.2.6"
1
+ __version__ = "0.2.8"
execnb/_modidx.py CHANGED
@@ -47,6 +47,7 @@ d = { 'settings': { 'branch': 'main',
47
47
  'execnb.shell.exec_nb': ('shell.html#exec_nb', 'execnb/shell.py'),
48
48
  'execnb.shell.find_output': ('shell.html#find_output', 'execnb/shell.py'),
49
49
  'execnb.shell.format_exc': ('shell.html#format_exc', 'execnb/shell.py'),
50
+ 'execnb.shell.leading_comment_lines': ('shell.html#leading_comment_lines', 'execnb/shell.py'),
50
51
  'execnb.shell.out_error': ('shell.html#out_error', 'execnb/shell.py'),
51
52
  'execnb.shell.out_exec': ('shell.html#out_exec', 'execnb/shell.py'),
52
53
  'execnb.shell.out_stream': ('shell.html#out_stream', 'execnb/shell.py'),
execnb/shell.py CHANGED
@@ -5,8 +5,8 @@ Docs: https://AnswerDotAI.github.io/execnb/shell.html.md"""
5
5
  # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_shell.ipynb.
6
6
 
7
7
  # %% auto #0
8
- __all__ = ['CaptureShell', 'format_exc', 'NbResult', 'render_outputs', 'find_output', 'out_exec', 'out_stream', 'out_error',
9
- 'select_cells', 'exec_nb', 'SmartCompleter']
8
+ __all__ = ['leading_comment_lines', 'CaptureShell', 'format_exc', 'NbResult', 'render_outputs', 'find_output', 'out_exec',
9
+ 'out_stream', 'out_error', 'select_cells', 'exec_nb', 'SmartCompleter']
10
10
 
11
11
  # %% ../nbs/00_shell.ipynb #535003cf
12
12
  from fastcore.utils import *
@@ -22,6 +22,7 @@ from traitlets.config import Config
22
22
  from traitlets.config.loader import PyFileConfigLoader
23
23
  from IPython.paths import get_ipython_dir
24
24
  from IPython.core.interactiveshell import InteractiveShell, ExecutionInfo, ExecutionResult
25
+ from IPython.core.error import UsageError
25
26
  from IPython.core.displayhook import DisplayHook
26
27
  from IPython.utils.capture import capture_output
27
28
  from IPython.core.completer import IPCompleter,provisionalcompleter
@@ -60,6 +61,12 @@ def _profile_cfg(name='default'):
60
61
  cfg.merge(c)
61
62
  return cfg,exts,pd
62
63
 
64
+ # %% ../nbs/00_shell.ipynb #62ece372
65
+ def leading_comment_lines(lines):
66
+ "Input cleanup transform: drop leading blank/comment lines when the first code line is a cell magic, which IPython otherwise misparses as a line magic"
67
+ i = next((i for i,l in enumerate(lines) if l.strip() and not l.lstrip().startswith('#')), 0)
68
+ return lines[i:] if i and lines[i].startswith('%%') else lines
69
+
63
70
  # %% ../nbs/00_shell.ipynb #e3fb2bee
64
71
  class CaptureShell(InteractiveShell):
65
72
  displayhook_class = _CustDisplayHook
@@ -68,9 +75,10 @@ class CaptureShell(InteractiveShell):
68
75
  cfg = _profile_cfg()[0] if profile else Config()
69
76
  if not history: cfg.HistoryManager.hist_file = ':memory:'
70
77
  super().__init__(config=cfg)
78
+ self.input_transformers_cleanup.append(leading_comment_lines)
71
79
  self.history_manager.enabled = history
72
80
  self.timeout = timeout
73
- self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
81
+ self.result,self.exc,self._cell_idx,self._fname,self._nested = None,None,None,None,False
74
82
  if path: self.set_path(path)
75
83
  self.display_formatter.active = True
76
84
  if not in_notebook(): InteractiveShell._instance = self
@@ -84,13 +92,27 @@ class CaptureShell(InteractiveShell):
84
92
  if profile: self.load_profile()
85
93
 
86
94
  def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
87
- stdout=True, stderr=True, display=True, verbose=False):
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`"
88
97
  # TODO what if there's a comment?
89
- semic = raw_cell.rstrip().endswith(';')
90
- with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
91
- result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
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.",)
92
114
  return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr, display_objects=c.outputs,
93
- exception=result.error_in_exec or result.error_before_exec, quiet=semic)
115
+ exception=e, quiet=semic)
94
116
 
95
117
  def set_path(self, path):
96
118
  "Add `path` to python path, or `path.parent` if it's a file"
@@ -104,15 +126,10 @@ class CaptureShell(InteractiveShell):
104
126
  @patch
105
127
  def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
106
128
  stdout=True, stderr=True, display=True, timeout=None, verbose=False):
107
- if not timeout: timeout = self.timeout
108
- if timeout:
109
- def handler(*args): raise TimeoutError()
110
- signal.signal(signal.SIGALRM, handler)
111
- signal.alarm(timeout)
112
- try: return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
113
- stdout=stdout, stderr=stderr, display=display, verbose=verbose)
114
- finally:
115
- if timeout: signal.alarm(0)
129
+ if self._nested: return super(CaptureShell, self).run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
130
+ return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
131
+ stdout=stdout, stderr=stderr, display=display, timeout=timeout, verbose=verbose)
132
+
116
133
 
117
134
  # %% ../nbs/00_shell.ipynb #a05e1b43
118
135
  @patch
@@ -174,26 +191,30 @@ def _out_nb(o, fmt):
174
191
 
175
192
  # %% ../nbs/00_shell.ipynb #242f732f
176
193
  @patch
177
- def run(self:CaptureShell,
194
+ def run(
195
+ self:CaptureShell,
178
196
  code:str, # Python/IPython code to run
179
197
  stdout=True, # Capture stdout and save as output?
180
198
  stderr=True, # Capture stderr and save as output?
181
199
  timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
182
- verbose:bool=False): # Show stdout/stderr during execution
200
+ verbose:bool=False # Show stdout/stderr during execution
201
+ ):
183
202
  "Run `code`, returning a list of all outputs in Jupyter notebook format"
184
- res = self.run_cell(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
203
+ res = self._run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
185
204
  self.result = res.result.result
186
205
  self.exc = res.exception
187
206
  return _out_nb(res, self.display_formatter)
188
207
 
189
208
  # %% ../nbs/00_shell.ipynb #eaa11df9
190
209
  @patch
191
- async def run_async(self:CaptureShell,
210
+ async def run_async(
211
+ self:CaptureShell,
192
212
  code: str, # Python/IPython code to run
193
213
  stdout=True, # Capture stdout and save as output?
194
214
  stderr=True, # Capture stderr and save as output?
195
215
  timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
196
- verbose:bool=False): # Show stdout/stderr during execution
216
+ verbose:bool=False # Show stdout/stderr during execution
217
+ ):
197
218
  return self.run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
198
219
 
199
220
  # %% ../nbs/00_shell.ipynb #f698a432
@@ -238,12 +259,13 @@ def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
238
259
  if cell.cell_type!='code': return
239
260
  self._cell_idx = cell.idx_ + 1
240
261
  outs = self.run(cell.source, verbose=verbose)
241
- if outs: cell.outputs = _dict2obj(outs)
262
+ cell.outputs = _dict2obj(outs) if outs else []
242
263
 
243
264
  # %% ../nbs/00_shell.ipynb #008c0cef
244
- def find_output(outp, # Output from `run`
265
+ def find_output(
266
+ outp, # Output from `run`
245
267
  ot='execute_result' # Output_type to find
246
- ):
268
+ ):
247
269
  "Find first output of type `ot` in `CaptureShell.run` output"
248
270
  return first(o for o in outp if o['output_type']==ot)
249
271
 
@@ -289,7 +311,8 @@ def run_all(
289
311
 
290
312
  # %% ../nbs/00_shell.ipynb #70808010
291
313
  @patch
292
- def execute(self:CaptureShell,
314
+ def execute(
315
+ self:CaptureShell,
293
316
  src:str|Path, # Notebook path to read from
294
317
  dest:str|None=None, # Notebook path to write to
295
318
  exc_stop:bool=False, # Stop on exceptions?
@@ -322,9 +345,9 @@ def prettytb(self:CaptureShell,
322
345
  return f"{type(self.exc).__name__}{fname_str}:\n{_fence}\n{cell_str}\n"
323
346
 
324
347
  # %% ../nbs/00_shell.ipynb #de6bd9f6
325
- def _is_exported(src): return bool(re.search(r'^\s*#\|\s*exports?\b', src, flags=re.M))
326
- def _is_noeval(src):
327
- return 'nbdev_export'+'(' in src or bool(re.search(r'^\s*#\|\s*eval:\s*false\s*$', src, flags=re.M|re.I))
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'
328
351
 
329
352
  def select_cells(
330
353
  nb, # A notebook read with `read_nb`
@@ -346,8 +369,8 @@ def select_cells(
346
369
  if above: cells = cells[:idx+1]
347
370
  elif below: cells = cells[idx:]
348
371
  else: cells = [cells[idx]]
349
- if exported: cells = [o for o in cells if _is_exported(o.source)]
350
- if skip_noeval: cells = [o for o in cells if not _is_noeval(o.source)]
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)]
351
374
  return cells
352
375
 
353
376
  # %% ../nbs/00_shell.ipynb #9c16e245
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.6
3
+ Version: 0.2.8
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>=1.10.4
18
+ Requires-Dist: fastcore>=2.1.2
19
19
  Requires-Dist: ipython
20
20
  Provides-Extra: dev
21
21
  Requires-Dist: matplotlib; extra == "dev"
@@ -28,9 +28,7 @@ Dynamic: license-file
28
28
 
29
29
  <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
30
30
 
31
- [![CI](https://github.com/fastai/execnb/actions/workflows/test.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/test.yaml)
32
- [![Deploy to GitHub
33
- Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
31
+ [![CI](https://github.com/fastai/execnb/actions/workflows/test.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/test.yaml) [![Deploy to GitHub Pages](https://github.com/fastai/execnb/actions/workflows/deploy.yaml/badge.svg)](https://github.com/fastai/execnb/actions/workflows/deploy.yaml)
34
32
 
35
33
  ## Install
36
34
 
@@ -42,15 +40,11 @@ or if you use conda:
42
40
 
43
41
  conda install -c fastai execnb
44
42
 
45
- (You can replace `conda` with `mamba` in the line above if you have
46
- mamba installed.)
43
+ (You can replace `conda` with `mamba` in the line above if you have mamba installed.)
47
44
 
48
45
  ## How to use
49
46
 
50
- Use
51
- [`CaptureShell`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell)
52
- to run Jupyter code and capture notebook outputs, without running a
53
- Jupyter server (or even having it installed):
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):
54
48
 
55
49
  ``` python
56
50
  from execnb.shell import *
@@ -68,8 +62,7 @@ s.run('1+1')
68
62
  'output_type': 'execute_result',
69
63
  'execution_count': None}]
70
64
 
71
- To execute a notebook and save it with outputs filled in, use
72
- [`CaptureShell.execute`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell.execute):
65
+ To execute a notebook and save it with outputs filled in, use [`CaptureShell.execute`](https://AnswerDotAI.github.io/execnb/shell.html#captureshell.execute):
73
66
 
74
67
  ``` python
75
68
  try:
@@ -78,10 +71,9 @@ try:
78
71
  finally: Path('tmp.ipynb').unlink()
79
72
  ```
80
73
 
81
- [{'name': 'stdout', 'output_type': 'stream', 'text': ['1\n']}, {'data': {'text/plain': ['2']}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}]
74
+ [{'name': 'stdout', 'output_type': 'stream', 'text': '1\n'}, {'data': {'text/plain': '2'}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}]
82
75
 
83
- You can also execute notebooks from the command line with
84
- [`exec_nb`](https://AnswerDotAI.github.io/execnb/shell.html#exec_nb):
76
+ You can also execute notebooks from the command line with [`exec_nb`](https://AnswerDotAI.github.io/execnb/shell.html#exec_nb):
85
77
 
86
78
  ``` python
87
79
  !exec_nb --help
@@ -0,0 +1,9 @@
1
+ execnb/__init__.py,sha256=G6Dbxq2ws-1ZAXwDD8q0KWueYtso_Y6Uyvtj8sRWsPI,22
2
+ execnb/_modidx.py,sha256=CGCE157AhQRJIdej9hutAZ-x6h0Y_yVA7GzkS2uC4o4,5748
3
+ execnb/shell.py,sha256=n0nzHbEOiNwU8SAPcXhJ--k4ih5wiYnYAf14CtwbF6Y,20159
4
+ execnb-0.2.8.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
+ execnb-0.2.8.dist-info/METADATA,sha256=I5K3T5-MO8g6LDVGsClOihGoq0yRGxbborE9aTVBVss,3456
6
+ execnb-0.2.8.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ execnb-0.2.8.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
8
+ execnb-0.2.8.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
9
+ execnb-0.2.8.dist-info/RECORD,,
@@ -1,9 +0,0 @@
1
- execnb/__init__.py,sha256=Oz5HbwHMyE87nmwV80AZzpkJPf-wBg7eDuJr_BXZkhU,22
2
- execnb/_modidx.py,sha256=hpN6T1XnbTJKPSZM9ap1ovDJkLVFfUk7dBuvPkeowIY,5623
3
- execnb/shell.py,sha256=bTcavwgann30aqyGHGaFOj2Jl2FAqTq89OKzqNVqlQs,18943
4
- execnb-0.2.6.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
- execnb-0.2.6.dist-info/METADATA,sha256=jFcqZDCy1GhjRIz06NjPu_BiiZhNKQ0rnGeqhCLtUyY,3461
6
- execnb-0.2.6.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
- execnb-0.2.6.dist-info/entry_points.txt,sha256=jZ8LPZCqnu4hXN_AgQpm05hVnTE-C25YK_4aiVX4i78,84
8
- execnb-0.2.6.dist-info/top_level.txt,sha256=VGWmzsw8FOlT1r5TdOxaTWIAyRdclcxNdJ2r1hojf5U,7
9
- execnb-0.2.6.dist-info/RECORD,,
File without changes