ipython笔记本中的自定义魔法 - 代码无法执行

时间:2016-06-28 18:01:42

标签: python ipython

我对ipython魔法相对较新,想要运行一些代码,同时通过魔术命令将其添加到列表中。魔法定义如下

#iPython notebook magic
from IPython.core.magic import  (
    Magics, magics_class, cell_magic, line_magic
)

@magics_class
class ReportMagic(Magics):
    def __init__(self, shell,  data):
        super(ReportMagic,self).__init__(shell)
        self._code_store = []
        self._markdown_store = []
        self._conf_code_store=[]
        self._conf_markdown_store=[]
        self.data = data
        # inject our store in user availlable namespace under __mystore
        # name
        shell.user_ns['__mycodestore'] = self._code_store
        shell.user_ns['__mymarkdownstore'] = self._markdown_store

    @cell_magic
    def add_code_to_report(self, line, cell):
        """store the cell in the store"""
        self._code_store.append(cell)

    @cell_magic
    def add_markdown_to_report(self, line, cell):
        """store the cell in the store"""
        self._markdown_store.append(cell)

    @cell_magic
    def add_conf_code_to_report(self, line, cell):
        """store the cell in the store"""
        self._conf_code_store.append(cell)

    @cell_magic
    def add_conf_markdown_to_report(self, line, cell):
        """store the cell in the store"""
        self._conf_markdown_store.append(cell)


    @line_magic
    def show_report(self, line):
        """show all recorded statements"""
        return self._conf_markdown_store,self._conf_code_store ,self._markdown_store,self._code_store

# This class must then be registered with a manually created instance,
# since its constructor has different arguments from the default:
ip = get_ipython()
magics = ReportMagic(ip, 0)
ip.register_magics(magics)

我正在按照以下方式调用魔法

%%add_conf_code_to_report

import pandas as pd
import numpy as np
import os
import collections

导入代码被复制到_conf_code_store,但我无法从导入的库中调用这些函数。 我希望代码应该添加到_conf_code_store中,同时导入的libaries的功能应该在笔记本中可用。

1 个答案:

答案 0 :(得分:0)

我已经能够解决它。 要通过magic函数执行代码,必须为ipython对象调用run_cell实例。可以有更好的方法,但代码现在可以使用。

@cell_magic
@needs_local_scope
def add_conf_code_to_report(self, line, cell):
    """store the cell in the store"""
    self._conf_code_store.append(cell)
    print type(cell)
    exec 'from IPython.core.display import HTML'
    for each in cell.split('\n'):
        print each
        exec repr(each.strip())
    ip=get_ipython()
    ip.run_cell(cell)