MCPcopy Create free account
hub / github.com/ipython/ipython / safe_execfile_ipy

Method safe_execfile_ipy

IPython/core/interactiveshell.py:2763–2820  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

2761 self.showtraceback(tb_offset=2)
2762
2763 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2764 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2765
2766 Parameters
2767 ----------
2768 fname : str
2769 The name of the file to execute. The filename must have a
2770 .ipy or .ipynb extension.
2771 shell_futures : bool (False)
2772 If True, the code will share future statements with the interactive
2773 shell. It will both be affected by previous __future__ imports, and
2774 any __future__ imports in the code will affect the shell. If False,
2775 __future__ imports are not shared in either direction.
2776 raise_exceptions : bool (False)
2777 If True raise exceptions everywhere. Meant for testing.
2778 """
2779 fname = os.path.abspath(os.path.expanduser(fname))
2780
2781 # Make sure we can open the file
2782 try:
2783 with open(fname):
2784 pass
2785 except:
2786 warn('Could not open file <%s> for safe execution.' % fname)
2787 return
2788
2789 # Find things also in current directory. This is needed to mimic the
2790 # behavior of running a script from the system command line, where
2791 # Python inserts the script's directory into sys.path
2792 dname = os.path.dirname(fname)
2793
2794 def get_cells():
2795 """generator for sequence of code blocks to run"""
2796 if fname.endswith('.ipynb'):
2797 from nbformat import read
2798 nb = read(fname, as_version=4)
2799 if not nb.cells:
2800 return
2801 for cell in nb.cells:
2802 if cell.cell_type == 'code':
2803 yield cell.source
2804 else:
2805 with open(fname) as f:
2806 yield f.read()
2807
2808 with prepended_to_syspath(dname):
2809 try:
2810 for cell in get_cells():
2811 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2812 if raise_exceptions:
2813 result.raise_error()
2814 elif not result.success:
2815 break
2816 except:
2817 if raise_exceptions:
2818 raise
2819 self.showtraceback()
2820 warn('Unknown failure executing file: <%s>' % fname)

Callers 2

_exec_fileMethod · 0.80
runMethod · 0.80

Calls 4

run_cellMethod · 0.95
showtracebackMethod · 0.95
raise_errorMethod · 0.80

Tested by

no test coverage detected