2017-08-08 190 views
1

我是初學者Jupyter。我有一個Python程序,使用nbformat execute API啓動我的筆記本。將參數傳遞給jupyter筆記本以nbformat開頭

它工作的很好,但有一件事我沒有設法弄清楚; 如何將我的程序中的數據傳遞到我即將執行的筆記本中?

爲了完整這裏是我用來運行筆記本代碼:

import nbformat 
from nbconvert.preprocessors import ExecutePreprocessor 

class NotebookExecutor: 
    def __init__(self, name, base_path, notebook_filename_in, notebook_filename_out, timeout=-1): 
     self.name = name 
     if base_path.endswith('/') is False: 
      base_path = base_path + '/' 
     self.base_path = base_path 
     self.notebook_filename_in = notebook_filename_in 
     self.notebook_filename_out = notebook_filename_out 
     self.timeout = timeout 

    def run(self): 
     print("Running notebook '" + self.name + "'") 
     nb = nbformat.read(open(self.base_path + self.notebook_filename_in), as_version=4) 
     ep = ExecutePreprocessor(timeout=self.timeout, kernel_name='python3', allow_errors=True) 
     try: 
      ep.preprocess(nb, {'metadata': {'path': self.base_path}}) 
     except CellExecutionError: 
      msg = 'Error executing the notebook "%s".\n\n' % self.notebook_filename_in 
      msg += 'See notebook "%s" for the traceback.' % self.notebook_filename_out 
      print(msg) 
     # raise 
     finally: 
      nbformat.write(nb, open(self.base_path + self.notebook_filename_out, mode='wt')) 

ne = NotebookExecutor('Test', '/my/path', 'MyBook.ipynb', 'MyBook_out.ipynb') 
ne.run() 

回答