Reusing code from different IPython notebooks

前端 未结 10 1208
南方客
南方客 2020-12-13 08:52

I am using IPython and want to run functions from one notebook from another (without cutting and pasting them between different notebooks). Is this possible and reasonably e

10条回答
  •  旧巷少年郎
    2020-12-13 09:17

    I do call notebooks from other notebooks. You can even pass "parameters" to other notebooks using the following trick:

    Place params dictionary in the first cell of "report_template.ipynb".

    params = dict(platform='iOS', 
                  start_date='2016-05-01', 
                  retention=7)
    df = get_data(params ..)
    do_analysis(params ..)
    

    And in another (higher logical level) notebook, execute it using this function:

    def run_notebook(nbfile, **kwargs):
        """
        example:
        run_notebook('report.ipynb', platform='google_play', start_date='2016-06-10')
        """
    
        def read_notebook(nbfile):
            if not nbfile.endswith('.ipynb'):
                nbfile += '.ipynb'
    
            with io.open(nbfile) as f:
                nb = nbformat.read(f, as_version=4)
            return nb
    
        ip = get_ipython()
        gl = ip.ns_table['user_global']
        gl['params'] = None
        arguments_in_original_state = True
    
        for cell in read_notebook(nbfile).cells:
            if cell.cell_type != 'code':
                continue
            ip.run_cell(cell.source)
    
            if arguments_in_original_state and type(gl['params']) == dict:
                gl['params'].update(kwargs)
                arguments_in_original_state = False
    
    run_notebook("report_template.ipynb", start_date='2016-09-01')
    

    This command will execute each cell of the "report_template" notebook and will override relevant keys of params dictionary starting from the second cell

提交回复
热议问题