2016-06-28 9 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に追加し、同時にインポートされたライブラリの機能をノートブックで利用できるようにしたいと思います。

答えて

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) 
関連する問題