python - 如何在 jupyter 中定义自定义魔法?

标签 python ipython jupyter-notebook ipython-magic

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

Python 3.5.1 :: Anaconda 2.4.1 (64-bit)

我正在尝试使用 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/startup

让它在笔记本电脑启动时自动加载,但我无法感受到它的魔力。谁能帮忙?

最佳答案

这里有两个独立的东西:

  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)

关于python - 如何在 jupyter 中定义自定义魔法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631454/

相关文章:

python - zeromq zmq.Poller & 标准输入

ipython - ipython 笔记本中的 tikz : no drawing created. 相反,获取消息 "No image generated."

python - 将字符串作为变量而不是可执行代码片段粘贴到 IPython 中

matplotlib - 如何在 Python 中将 2D DICOM 切片转换为 3D 图像

python - 未解析的外部符号构建 Python C 扩展

python - "Splat"行,列表分为多行(pandas)

python - 如何从 Python 中的字符串中提取字符?

ipython - ipython 的 atexit 替代品

python - Datalab 到 BigQuery - 将变量值插入 SQL 中

python - 如何在 Jupyter Notebook 启动时运行自定义 Python 脚本(以启动 Spark)?