execnb 0.2.3__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -0,0 +1 @@
1
+ __version__ = "0.2.5"
@@ -12,6 +12,7 @@ d = { 'settings': { 'branch': 'main',
12
12
  'execnb.shell.CaptureShell.complete': ('shell.html#captureshell.complete', 'execnb/shell.py'),
13
13
  'execnb.shell.CaptureShell.enable_gui': ('shell.html#captureshell.enable_gui', 'execnb/shell.py'),
14
14
  'execnb.shell.CaptureShell.execute': ('shell.html#captureshell.execute', 'execnb/shell.py'),
15
+ 'execnb.shell.CaptureShell.load_profile': ('shell.html#captureshell.load_profile', 'execnb/shell.py'),
15
16
  'execnb.shell.CaptureShell.nbopen': ('shell.html#captureshell.nbopen', 'execnb/shell.py'),
16
17
  'execnb.shell.CaptureShell.nbrun': ('shell.html#captureshell.nbrun', 'execnb/shell.py'),
17
18
  'execnb.shell.CaptureShell.prettytb': ('shell.html#captureshell.prettytb', 'execnb/shell.py'),
@@ -35,11 +36,13 @@ d = { 'settings': { 'branch': 'main',
35
36
  'execnb.shell._false': ('shell.html#_false', 'execnb/shell.py'),
36
37
  'execnb.shell._format_mimedata': ('shell.html#_format_mimedata', 'execnb/shell.py'),
37
38
  'execnb.shell._is_exported': ('shell.html#_is_exported', 'execnb/shell.py'),
39
+ 'execnb.shell._is_noeval': ('shell.html#_is_noeval', 'execnb/shell.py'),
38
40
  'execnb.shell._mk_out': ('shell.html#_mk_out', 'execnb/shell.py'),
39
41
  'execnb.shell._out_exc': ('shell.html#_out_exc', 'execnb/shell.py'),
40
42
  'execnb.shell._out_nb': ('shell.html#_out_nb', 'execnb/shell.py'),
41
43
  'execnb.shell._out_stream': ('shell.html#_out_stream', 'execnb/shell.py'),
42
44
  'execnb.shell._pre': ('shell.html#_pre', 'execnb/shell.py'),
45
+ 'execnb.shell._profile_cfg': ('shell.html#_profile_cfg', 'execnb/shell.py'),
43
46
  'execnb.shell._strip': ('shell.html#_strip', 'execnb/shell.py'),
44
47
  'execnb.shell.exec_nb': ('shell.html#exec_nb', 'execnb/shell.py'),
45
48
  'execnb.shell.find_output': ('shell.html#find_output', 'execnb/shell.py'),
@@ -1,6 +1,6 @@
1
1
  """A shell for running notebook code without a notebook server
2
2
 
3
- Docs: https://AnswerDotAI.github.io/execnbshell.html.md"""
3
+ Docs: https://AnswerDotAI.github.io/execnb/shell.html.md"""
4
4
 
5
5
  # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_shell.ipynb.
6
6
 
@@ -11,21 +11,23 @@ __all__ = ['CaptureShell', 'format_exc', 'NbResult', 'render_outputs', 'find_out
11
11
  # %% ../nbs/00_shell.ipynb #535003cf
12
12
  from fastcore.utils import *
13
13
  from fastcore.script import call_parse
14
- from fastcore.ansi import ansi2html, strip_ansi
14
+ from fastcore.ansi import strip_ansi
15
15
 
16
16
  import multiprocessing,types,traceback,signal
17
17
  try:
18
18
  if sys.platform == 'darwin': multiprocessing.set_start_method("fork")
19
19
  except RuntimeError: pass # if re-running cell
20
20
 
21
+ from traitlets.config import Config
22
+ from traitlets.config.loader import PyFileConfigLoader
23
+ from IPython.paths import get_ipython_dir
21
24
  from IPython.core.interactiveshell import InteractiveShell, ExecutionInfo, ExecutionResult
22
25
  from IPython.core.displayhook import DisplayHook
23
26
  from IPython.utils.capture import capture_output
24
- from IPython.core.completer import IPCompleter,provisionalcompleter,Completer
27
+ from IPython.core.completer import IPCompleter,provisionalcompleter
25
28
  from IPython.core.hooks import CommandChainDispatcher
26
29
  from IPython.core.completerlib import module_completer
27
30
  from IPython.utils.strdispatch import StrDispatch
28
- from IPython.display import display as disp, HTML
29
31
 
30
32
  from base64 import b64encode
31
33
  from html import escape
@@ -33,7 +35,6 @@ from html import escape
33
35
  from fastcore.nbio import *
34
36
  from fastcore.nbio import _dict2obj
35
37
 
36
-
37
38
  # %% ../nbs/00_shell.ipynb #6913382c
38
39
  class _CustDisplayHook(DisplayHook):
39
40
  def write_output_prompt(self): pass
@@ -46,15 +47,30 @@ def __repr__(self: ExecutionInfo): return f'cell: {self.raw_cell}; id: {self.cel
46
47
  @patch
47
48
  def __repr__(self: ExecutionResult): return f'result: {self.result}; err: {self.error_in_exec}; info: <{self.info}>'
48
49
 
50
+ # %% ../nbs/00_shell.ipynb #9c879b74
51
+ def _profile_cfg(name='default'):
52
+ "Merged config, extensions, and profile dir for IPython profile `name`"
53
+ pd = Path(get_ipython_dir())/f'profile_{name}'
54
+ cfg,exts = Config(),[]
55
+ for f in ('ipython_config.py','ipython_kernel_config.py'):
56
+ if not (pd/f).exists(): continue
57
+ c = PyFileConfigLoader(f, path=str(pd)).load_config()
58
+ e = c.get('InteractiveShellApp', {}).get('extensions', [])
59
+ exts += e.get_value([]) if hasattr(e, 'get_value') else e
60
+ cfg.merge(c)
61
+ return cfg,exts,pd
62
+
49
63
  # %% ../nbs/00_shell.ipynb #e3fb2bee
50
64
  class CaptureShell(InteractiveShell):
51
65
  displayhook_class = _CustDisplayHook
52
66
 
53
- def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None):
54
- super().__init__()
67
+ def __init__(self, path:str|Path=None, mpl_format='retina', history=False, timeout:Optional[int]=None, profile:bool=False):
68
+ cfg = _profile_cfg()[0] if profile else Config()
69
+ if not history: cfg.HistoryManager.hist_file = ':memory:'
70
+ super().__init__(config=cfg)
55
71
  self.history_manager.enabled = history
56
72
  self.timeout = timeout
57
- self.result,self.exc = None,None
73
+ self.result,self.exc,self._cell_idx,self._fname = None,None,None,None
58
74
  if path: self.set_path(path)
59
75
  self.display_formatter.active = True
60
76
  if not in_notebook(): InteractiveShell._instance = self
@@ -65,16 +81,16 @@ class CaptureShell(InteractiveShell):
65
81
  self.enable_matplotlib("inline")
66
82
  self._run("from matplotlib_inline.backend_inline import set_matplotlib_formats")
67
83
  self._run(f"set_matplotlib_formats('{mpl_format}')")
84
+ if profile: self.load_profile()
68
85
 
69
86
  def _run(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
70
- stdout=True, stderr=True, display=True, verbose=False):
87
+ stdout=True, stderr=True, display=True, verbose=False):
71
88
  # TODO what if there's a comment?
72
89
  semic = raw_cell.rstrip().endswith(';')
73
90
  with capture_output(display=display, stdout=stdout and not verbose, stderr=stderr and not verbose) as c:
74
91
  result = super().run_cell(raw_cell, store_history, silent, shell_futures=shell_futures, cell_id=cell_id)
75
- return AttrDict(result=result, stdout='' if semic else c.stdout, stderr=c.stderr,
76
- display_objects=c.outputs,
77
- exception=result.error_in_exec or result.error_before_exec, quiet=semic)
92
+ 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)
78
94
 
79
95
  def set_path(self, path):
80
96
  "Add `path` to python path, or `path.parent` if it's a file"
@@ -87,17 +103,35 @@ class CaptureShell(InteractiveShell):
87
103
  # %% ../nbs/00_shell.ipynb #93adf867
88
104
  @patch
89
105
  def run_cell(self:CaptureShell, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None,
90
- stdout=True, stderr=True, display=True, timeout=None, verbose=False):
106
+ stdout=True, stderr=True, display=True, timeout=None, verbose=False):
91
107
  if not timeout: timeout = self.timeout
92
108
  if timeout:
93
109
  def handler(*args): raise TimeoutError()
94
110
  signal.signal(signal.SIGALRM, handler)
95
111
  signal.alarm(timeout)
96
112
  try: return self._run(raw_cell, store_history, silent, shell_futures, cell_id=cell_id,
97
- stdout=stdout, stderr=stderr, display=display, verbose=verbose)
113
+ stdout=stdout, stderr=stderr, display=display, verbose=verbose)
98
114
  finally:
99
115
  if timeout: signal.alarm(0)
100
116
 
117
+ # %% ../nbs/00_shell.ipynb #a05e1b43
118
+ @patch
119
+ def load_profile(self:CaptureShell, name='default'):
120
+ "Load profile `name`'s extensions and run its startup files (output suppressed), as `ipykernel` does"
121
+ cfg,exts,pd = _profile_cfg(name)
122
+ warns = []
123
+ with capture_output():
124
+ for o in exts:
125
+ try: self.extension_manager.load_extension(o)
126
+ except Exception as e: warns.append(f"Failed loading extension {o}: {e}")
127
+ sd = pd/'startup'
128
+ for f in sorted([*sd.glob('*.py'), *sd.glob('*.ipy')]) if sd.is_dir() else []:
129
+ try:
130
+ if f.suffix=='.ipy': self.safe_execfile_ipy(f, raise_exceptions=True)
131
+ else: self.safe_execfile(f, self.user_ns, raise_exceptions=True)
132
+ except Exception as e: warns.append(f"Failed running startup file {f}: {e}")
133
+ for w in warns: warnings.warn(w)
134
+
101
135
  # %% ../nbs/00_shell.ipynb #a1eb7703
102
136
  def format_exc(e):
103
137
  "Format exception `e` as a string list"
@@ -132,8 +166,7 @@ def _out_nb(o, fmt):
132
166
  if o.exception: res.append(_out_exc(o.exception))
133
167
  res.result = o.result.result
134
168
  for x in o.display_objects: res.append(_mk_out(x.data, x.metadata))
135
- if res.result is not None and not o.quiet:
136
- res.append(_mk_out(*fmt.format(res.result), 'execute_result'))
169
+ if res.result is not None and not o.quiet: res.append(_mk_out(*fmt.format(res.result), 'execute_result'))
137
170
  if 'execution_count' not in o: o['execution_count']=None
138
171
  for p in res:
139
172
  if p["output_type"]=="execute_result": p['execution_count'] = o['execution_count']
@@ -142,11 +175,11 @@ def _out_nb(o, fmt):
142
175
  # %% ../nbs/00_shell.ipynb #242f732f
143
176
  @patch
144
177
  def run(self:CaptureShell,
145
- code:str, # Python/IPython code to run
146
- stdout=True, # Capture stdout and save as output?
147
- stderr=True, # Capture stderr and save as output?
148
- timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
149
- verbose:bool=False): # Show stdout/stderr during execution
178
+ code:str, # Python/IPython code to run
179
+ stdout=True, # Capture stdout and save as output?
180
+ stderr=True, # Capture stderr and save as output?
181
+ timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
182
+ verbose:bool=False): # Show stdout/stderr during execution
150
183
  "Run `code`, returning a list of all outputs in Jupyter notebook format"
151
184
  res = self.run_cell(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
152
185
  self.result = res.result.result
@@ -156,11 +189,11 @@ def run(self:CaptureShell,
156
189
  # %% ../nbs/00_shell.ipynb #eaa11df9
157
190
  @patch
158
191
  async def run_async(self:CaptureShell,
159
- code: str, # Python/IPython code to run
160
- stdout=True, # Capture stdout and save as output?
161
- stderr=True, # Capture stderr and save as output?
162
- timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
163
- verbose:bool=False): # Show stdout/stderr during execution
192
+ code: str, # Python/IPython code to run
193
+ stdout=True, # Capture stdout and save as output?
194
+ stderr=True, # Capture stderr and save as output?
195
+ timeout:Optional[int]=None, # Shell command will time out after {timeout} seconds
196
+ verbose:bool=False): # Show stdout/stderr during execution
164
197
  return self.run(code, stdout=stdout, stderr=stderr, timeout=timeout, verbose=verbose)
165
198
 
166
199
  # %% ../nbs/00_shell.ipynb #f698a432
@@ -209,7 +242,7 @@ def cell(self:CaptureShell, cell, stdout=True, stderr=True, verbose=False):
209
242
 
210
243
  # %% ../nbs/00_shell.ipynb #008c0cef
211
244
  def find_output(outp, # Output from `run`
212
- ot='execute_result' # Output_type to find
245
+ ot='execute_result' # Output_type to find
213
246
  ):
214
247
  "Find first output of type `ot` in `CaptureShell.run` output"
215
248
  return first(o for o in outp if o['output_type']==ot)
@@ -257,15 +290,15 @@ def run_all(
257
290
  # %% ../nbs/00_shell.ipynb #70808010
258
291
  @patch
259
292
  def execute(self:CaptureShell,
260
- src:str|Path, # Notebook path to read from
261
- dest:str|None=None, # Notebook path to write to
262
- exc_stop:bool=False, # Stop on exceptions?
263
- preproc:callable=_false, # Called before each cell is executed
264
- postproc:callable=_false, # Called after each cell is executed
265
- inject_code:str|None=None, # Code to inject into a cell
266
- inject_path:str|Path|None=None, # Path to file containing code to inject into a cell
267
- inject_idx:int=0, # Cell to replace with `inject_code`
268
- verbose:bool=False # Show stdout/stderr during execution
293
+ src:str|Path, # Notebook path to read from
294
+ dest:str|None=None, # Notebook path to write to
295
+ exc_stop:bool=False, # Stop on exceptions?
296
+ preproc:callable=_false, # Called before each cell is executed
297
+ postproc:callable=_false, # Called after each cell is executed
298
+ inject_code:str|None=None, # Code to inject into a cell
299
+ inject_path:str|Path|None=None, # Path to file containing code to inject into a cell
300
+ inject_idx:int=0, # Cell to replace with `inject_code`
301
+ verbose:bool=False # Show stdout/stderr during execution
269
302
  ):
270
303
  "Execute notebook from `src` and save with outputs to `dest"
271
304
  nb = read_nb(src)
@@ -273,13 +306,13 @@ def execute(self:CaptureShell,
273
306
  self.set_path(Path(src).parent.resolve())
274
307
  if inject_path is not None: inject_code = Path(inject_path).read_text()
275
308
  self.run_all(nb, exc_stop=exc_stop, preproc=preproc, postproc=postproc,
276
- inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
309
+ inject_code=inject_code, inject_idx=inject_idx, verbose=verbose)
277
310
  if dest: write_nb(nb, dest)
278
311
 
279
312
  # %% ../nbs/00_shell.ipynb #694161cb
280
313
  @patch
281
314
  def prettytb(self:CaptureShell,
282
- fname:str|Path=None): # filename to print alongside the traceback
315
+ fname:str|Path=None): # filename to print alongside the traceback
283
316
  "Show a pretty traceback for notebooks, optionally printing `fname`."
284
317
  fname = fname if fname else self._fname
285
318
  _fence = '='*75
@@ -290,6 +323,8 @@ def prettytb(self:CaptureShell,
290
323
 
291
324
  # %% ../nbs/00_shell.ipynb #de6bd9f6
292
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))
293
328
 
294
329
  def select_cells(
295
330
  nb, # A notebook read with `read_nb`
@@ -297,7 +332,8 @@ def select_cells(
297
332
  above:bool=False, # Include the matched cell and all cells above it?
298
333
  below:bool=False, # Include the matched cell and all cells below it?
299
334
  all:bool=False, # Include all code cells (ignores `msgid`)?
300
- exported:bool=False # Only cells with `#| export` or `#| exports`?
335
+ exported:bool=False, # Only cells with `#| export` or `#| exports`?
336
+ skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
301
337
  ):
302
338
  "Select code cells from `nb` by cell id prefix"
303
339
  cells = [o for o in nb.cells if o.cell_type=='code']
@@ -309,6 +345,7 @@ def select_cells(
309
345
  elif below: cells = cells[idx:]
310
346
  else: cells = [cells[idx]]
311
347
  if exported: cells = [o for o in cells if _is_exported(o.source)]
348
+ if skip_noeval: cells = [o for o in cells if not _is_noeval(o.source)]
312
349
  return cells
313
350
 
314
351
  # %% ../nbs/00_shell.ipynb #9c16e245
@@ -328,14 +365,15 @@ def nbrun(
328
365
  above:bool=False, # Also run all cells above the match?
329
366
  below:bool=False, # Also run all cells below the match?
330
367
  all:bool=False, # Run all code cells?
331
- exported:bool=False # Only cells with `#| export` or `#| exports`?
368
+ exported:bool=False, # Only cells with `#| export` or `#| exports`?
369
+ skip_noeval:bool=False # Skip `#| eval: false` and `nbdev_export` cells (like `nbdev-test`)?
332
370
  ):
333
371
  "Run cell(s) from a notebook by id prefix, printing rendered outputs"
334
372
  fname = ifnone(fname, getattr(self,'_nbrun_fname',None))
335
373
  if not fname: raise ValueError('No `fname` passed and no notebook opened with `nbopen`')
336
374
  self.nbopen(fname)
337
375
  nb = read_nb(fname)
338
- for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported):
376
+ for cell in select_cells(nb, msgid, above=above, below=below, all=all, exported=exported, skip_noeval=skip_noeval):
339
377
  res = render_text(self.run(cell.source))
340
378
  if res: print(f'--- {cell.id} ---\n{res}')
341
379
 
@@ -352,7 +390,7 @@ def exec_nb(
352
390
  ):
353
391
  "Execute notebook from `src` and save with outputs to `dest`"
354
392
  CaptureShell().execute(src, dest, exc_stop=exc_stop, inject_code=inject_code,
355
- inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
393
+ inject_path=inject_path, inject_idx=inject_idx, verbose=verbose)
356
394
 
357
395
  # %% ../nbs/00_shell.ipynb #c44963a0
358
396
  class SmartCompleter(IPCompleter):
@@ -369,8 +407,7 @@ class SmartCompleter(IPCompleter):
369
407
 
370
408
  def __call__(self, c):
371
409
  if not c: return []
372
- with provisionalcompleter():
373
- res = [o.text.rpartition('.')[-1] for o in self.completions(c, len(c)) if o.type!='magic']
410
+ with provisionalcompleter(): res = [o.text.rpartition('.')[-1] for o in self.completions(c, len(c)) if o.type!='magic']
374
411
  if res and res[0][-1]=='=': res = [o for o in res if o[-1]=='=']
375
412
  return res
376
413
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: execnb
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: A description of your project
5
5
  Author-email: Jeremy Howard <j@fast.ai>
6
6
  License: Apache-2.0
@@ -40,3 +40,6 @@ allowed_cell_metadata_keys = ['solveit_ai']
40
40
  recursive = false
41
41
  jupyter_hooks = true
42
42
  custom_sidebar = false
43
+
44
+ [tool.chkstyle]
45
+ skip_paths = ["_modidx.py"]
@@ -1 +0,0 @@
1
- __version__ = "0.2.3"
File without changes
File without changes
File without changes
File without changes