Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy or .ipynb extension. shell_futures : bool (False) If True, the
(self, fname, shell_futures=False, raise_exceptions=False)
| 2998 | self.showtraceback(tb_offset=2) |
| 2999 | |
| 3000 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
| 3001 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
| 3002 | |
| 3003 | Parameters |
| 3004 | ---------- |
| 3005 | fname : str |
| 3006 | The name of the file to execute. The filename must have a |
| 3007 | .ipy or .ipynb extension. |
| 3008 | shell_futures : bool (False) |
| 3009 | If True, the code will share future statements with the interactive |
| 3010 | shell. It will both be affected by previous __future__ imports, and |
| 3011 | any __future__ imports in the code will affect the shell. If False, |
| 3012 | __future__ imports are not shared in either direction. |
| 3013 | raise_exceptions : bool (False) |
| 3014 | If True raise exceptions everywhere. Meant for testing. |
| 3015 | """ |
| 3016 | fname = Path(fname).expanduser().resolve() |
| 3017 | |
| 3018 | # Make sure we can open the file |
| 3019 | try: |
| 3020 | with fname.open("rb"): |
| 3021 | pass |
| 3022 | except OSError: |
| 3023 | warn('Could not open file <%s> for safe execution.' % fname) |
| 3024 | return |
| 3025 | |
| 3026 | # Find things also in current directory. This is needed to mimic the |
| 3027 | # behavior of running a script from the system command line, where |
| 3028 | # Python inserts the script's directory into sys.path |
| 3029 | dname = str(fname.parent) |
| 3030 | |
| 3031 | def get_cells(): |
| 3032 | """generator for sequence of code blocks to run""" |
| 3033 | if fname.suffix == ".ipynb": |
| 3034 | from nbformat import read |
| 3035 | nb = read(fname, as_version=4) |
| 3036 | if not nb.cells: |
| 3037 | return |
| 3038 | for cell in nb.cells: |
| 3039 | if cell.cell_type == 'code': |
| 3040 | yield cell.source |
| 3041 | else: |
| 3042 | yield fname.read_text(encoding="utf-8") |
| 3043 | |
| 3044 | with prepended_to_syspath(dname): |
| 3045 | try: |
| 3046 | for cell in get_cells(): |
| 3047 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
| 3048 | if raise_exceptions: |
| 3049 | result.raise_error() |
| 3050 | elif not result.success: |
| 3051 | break |
| 3052 | except: |
| 3053 | if raise_exceptions: |
| 3054 | raise |
| 3055 | self.showtraceback() |
| 3056 | warn('Unknown failure executing file: <%s>' % fname) |
| 3057 |
no test coverage detected