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