##// END OF EJS Templates
Merge pull request #4452 from minrk/nbrun...
Thomas Kluyver -
r13648:b374d27f merge
parent child Browse files
Show More
@@ -0,0 +1,1 b''
1 * You can now run notebooks in an interactive session via ``%run notebook.ipynb``. No newline at end of file
@@ -54,7 +54,7 b" import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'"
54 r'|'.join(re.escape(s[0]) for s in imp.get_suffixes()))
54 r'|'.join(re.escape(s[0]) for s in imp.get_suffixes()))
55
55
56 # RE for the ipython %run command (python + ipython scripts)
56 # RE for the ipython %run command (python + ipython scripts)
57 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
57 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Local utilities
60 # Local utilities
@@ -250,7 +250,7 b' def module_completer(self,event):'
250 # completers, that is currently reimplemented in each.
250 # completers, that is currently reimplemented in each.
251
251
252 def magic_run_completer(self, event):
252 def magic_run_completer(self, event):
253 """Complete files that end in .py or .ipy for the %run command.
253 """Complete files that end in .py or .ipy or .ipynb for the %run command.
254 """
254 """
255 comps = arg_split(event.line, strict=False)
255 comps = arg_split(event.line, strict=False)
256 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
256 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
@@ -274,7 +274,7 b' def magic_run_completer(self, event):'
274 else:
274 else:
275 pys = [f.replace('\\','/')
275 pys = [f.replace('\\','/')
276 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
276 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
277 lglob(relpath + '*.pyw')]
277 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
278 #print('run comp:', dirs+pys) # dbg
278 #print('run comp:', dirs+pys) # dbg
279 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
279 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
280
280
@@ -2536,13 +2536,13 b' class InteractiveShell(SingletonConfigurable):'
2536 self.showtraceback()
2536 self.showtraceback()
2537
2537
2538 def safe_execfile_ipy(self, fname):
2538 def safe_execfile_ipy(self, fname):
2539 """Like safe_execfile, but for .ipy files with IPython syntax.
2539 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2540
2540
2541 Parameters
2541 Parameters
2542 ----------
2542 ----------
2543 fname : str
2543 fname : str
2544 The name of the file to execute. The filename must have a
2544 The name of the file to execute. The filename must have a
2545 .ipy extension.
2545 .ipy or .ipynb extension.
2546 """
2546 """
2547 fname = os.path.abspath(os.path.expanduser(fname))
2547 fname = os.path.abspath(os.path.expanduser(fname))
2548
2548
@@ -2558,15 +2558,29 b' class InteractiveShell(SingletonConfigurable):'
2558 # behavior of running a script from the system command line, where
2558 # behavior of running a script from the system command line, where
2559 # Python inserts the script's directory into sys.path
2559 # Python inserts the script's directory into sys.path
2560 dname = os.path.dirname(fname)
2560 dname = os.path.dirname(fname)
2561
2562 def get_cells():
2563 """generator for sequence of code blocks to run"""
2564 if fname.endswith('.ipynb'):
2565 from IPython.nbformat import current
2566 with open(fname) as f:
2567 nb = current.read(f, 'json')
2568 if not nb.worksheets:
2569 return
2570 for cell in nb.worksheets[0].cells:
2571 yield cell.input
2572 else:
2573 with open(fname) as f:
2574 yield f.read()
2561
2575
2562 with prepended_to_syspath(dname):
2576 with prepended_to_syspath(dname):
2563 try:
2577 try:
2564 with open(fname) as thefile:
2578 for cell in get_cells():
2565 # self.run_cell currently captures all exceptions
2579 # self.run_cell currently captures all exceptions
2566 # raised in user code. It would be nice if there were
2580 # raised in user code. It would be nice if there were
2567 # versions of runlines, execfile that did raise, so
2581 # versions of run_cell that did raise, so
2568 # we could catch the errors.
2582 # we could catch the errors.
2569 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2583 self.run_cell(cell, store_history=False, shell_futures=False)
2570 except:
2584 except:
2571 self.showtraceback()
2585 self.showtraceback()
2572 warn('Unknown failure executing file: <%s>' % fname)
2586 warn('Unknown failure executing file: <%s>' % fname)
@@ -552,7 +552,7 b' python-profiler package from non-free.""")'
552 details on the options available specifically for profiling.
552 details on the options available specifically for profiling.
553
553
554 There is one special usage for which the text above doesn't apply:
554 There is one special usage for which the text above doesn't apply:
555 if the filename ends with .ipy, the file is run as ipython script,
555 if the filename ends with .ipy[nb], the file is run as ipython script,
556 just as if the commands were written on IPython prompt.
556 just as if the commands were written on IPython prompt.
557
557
558 -m
558 -m
@@ -596,7 +596,7 b' python-profiler package from non-free.""")'
596 error(msg)
596 error(msg)
597 return
597 return
598
598
599 if filename.lower().endswith('.ipy'):
599 if filename.lower().endswith(('.ipy', '.ipynb')):
600 with preserve_keys(self.shell.user_ns, '__file__'):
600 with preserve_keys(self.shell.user_ns, '__file__'):
601 self.shell.user_ns['__file__'] = filename
601 self.shell.user_ns['__file__'] = filename
602 self.shell.safe_execfile_ipy(filename)
602 self.shell.safe_execfile_ipy(filename)
@@ -370,6 +370,23 b' tclass.py: deleting object: C-third'
370
370
371 with tt.AssertNotPrints('SystemExit'):
371 with tt.AssertNotPrints('SystemExit'):
372 _ip.magic('run -e %s' % self.fname)
372 _ip.magic('run -e %s' % self.fname)
373
374 def test_run_nb(self):
375 """Test %run notebook.ipynb"""
376 from IPython.nbformat import current
377 nb = current.new_notebook(
378 worksheets=[
379 current.new_worksheet(cells=[
380 current.new_code_cell("answer=42")
381 ])
382 ]
383 )
384 src = current.writes(nb, 'json')
385 self.mktmp(src, ext='.ipynb')
386
387 _ip.magic("run %s" % self.fname)
388
389 nt.assert_equal(_ip.user_ns['answer'], 42)
373
390
374
391
375
392
General Comments 0
You need to be logged in to leave comments. Login now