簡體   English   中英

ipython筆記本中的自定義魔法 - 代碼無法執行

[英]Custom magic in ipython notebooks - Code does not execute

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

我已經能夠解決它。 要通過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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM