2016-06-28 21 views
1

我對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的功能應該在筆記本中可用。

回答

0

我已經能夠解決它。 要通過魔術功能執行代碼,必須調用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)