【问题标题】:How do I define custom magics in jupyter?如何在 jupyter 中定义自定义魔法?
【发布时间】:2016-01-06 10:59:35
【问题描述】:

我正在使用 Ubuntu 14.04 LTS 和 Anaconda python 安装:

Python 3.5.1 :: Anaconda 2.4.1(64 位)

我正在尝试使用this recipe 在我的 ipython 笔记本中启用 C++ 交互式编译:

import IPython.core.magic as ipym

@ipym.magics_class
class CppMagics(ipym.Magics):
    @ipym.cell_magic
    def cpp(self, line, cell=None):
        """Compile, execute C++ code, and return the standard output."""
        # Define the source and executable filenames.
        source_filename = 'temp.cpp'
        program_filename = 'temp.exe'
        # Write the code contained in the cell to the C++ file.
        with open(source_filename, 'w') as f:
            f.write(cell)
        # Compile the C++ code into an executable.
        compile = self.shell.getoutput("g++ {0:s} -o {1:s}".format(
            source_filename, program_filename))
        # Execute the executable and return the output.
        output = self.shell.getoutput(program_filename)
        return output

def load_ipython_extension(ipython):
    ipython.register_magics(CppMagics)

当我使用以下命令执行单元格时,无论我使用 ipython notebok 还是 jupyter notebook(我相信第二个别名)启动我的笔记本:

%load_ext cppmagic

我收到以下错误:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-7b90c7a2b808> in <module>()
----> 1 get_ipython().magic('load_ext cppmagic')

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2334         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2335         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2336         return self.run_line_magic(magic_name, magic_arg_s)
   2337 
   2338     #-------------------------------------------------------------------------

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2255                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2256             with self.builtin_trap:
-> 2257                 result = fn(*args,**kwargs)
   2258             return result
   2259 

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str)

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str)
     64         if not module_str:
     65             raise UsageError('Missing module name.')
---> 66         res = self.shell.extension_manager.load_extension(module_str)
     67 
     68         if res == 'already loaded':

/home/norah/anaconda3/lib/python3.5/site-packages/IPython/core/extensions.py in load_extension(self, module_str)
     87             if module_str not in sys.modules:
     88                 with prepended_to_syspath(self.ipython_extension_dir):
---> 89                     __import__(module_str)
     90             mod = sys.modules[module_str]
     91             if self._call_load_ipython_extension(mod):

ImportError: No module named 'cppmagic'

配方中的代码似乎与the official docs 一致(均使用IPython.core.magic.magics_class)我已将我的cppmagic.py 放在以下目录中

~/.ipython/profile_default/启动

让它在笔记本启动时自动加载,但我感觉不到它的魔力。有人可以帮忙吗?

【问题讨论】:

    标签: python ipython ipython-notebook ipython-magic jupyter-notebook


    【解决方案1】:

    这里有两个不同的东西:

    1. 启动文件~/.ipython/profile_[name]/startup中的脚本,作为启动IPython的一部分执行。在第一个In[1] 提示之前,它们被视为您每个%run。无法导入启动文件,因为它们不在 sys.path 上。
    2. extensions 是可以导入并定义load_ipython_extension 函数的Python 模块。您可以将扩展放在~/.ipython/extensions 中,它们将是可导入的,或者您可以使用pip 将它们安装为常规包。

    第一个修复方法是将您的 cppmagics 移动到 ~/.ipython/extensions 或某个 site-packages 目录,以便可以导入。

    如果您真的希望始终注册魔法(而不是调用 %load_ext cppmagic),您可以将其保留为启动文件并在脚本末尾注册魔法,而不是 def load_ipython_extension

    if __name__ == '__main__':
        from IPython import get_ipython
        get_ipython().register_magics(CppMagics)
    

    【讨论】:

    • 非常感谢。这行得通!不幸的是,配方没有....我收到['/bin/sh: 1: temp.exe: not found'] 错误,但这与配方代码本身有关。我正在选择这个答案,如果你能帮助我解决我的上一个问题,我会很高兴。
    • 您可能想添加一个./temp.exe 以确保它在本地目录中查找,我不确定。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多