我对Ipython Magics是相对较新的,并且想运行一些代码并同时通过魔术命令将其添加到列表中。魔法定义如下
#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的功能。
我已经能够围绕它进行工作。要通过魔术函数执行代码,必须调用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)