简体   繁体   English

使用魔术功能自动执行一组命令/导入

[英]Automatically do a set of commands/imports with a magic function

I create a lot of different notebooks during my analyses. 在我的分析过程中,我创建了许多不同的笔记本。 However every notebook starts with the same imports and other statements. 但是,每个笔记本都以相同的导入和其他语句开头。 Most generally the following lines of code are my standard input for the first cell: 最常见的是以下代码行是我对第一个单元格的标准输入:

import pandas as pd
import numpy as np
.. otherimports

import sys
sys.path.append('../..')
... more imports from this directory

%matplotlib inline
%load_ext autoreload
%autoreload 2

I've grown tired of either copy pasting or manually typing this stuff for every notebook and am now trying to find an automated way of doing this. 我已经厌倦了复制粘贴或手动为每个笔记本键入这些东西,我现在正试图找到一种自动化的方式来做到这一点。

I looked at ipython extensions, so i could just call 我查看了ipython扩展,所以我可以打电话

%load_ext setup_analysis

but can't manage to effectively import stuff into the user environment using such an ipython extension. 但是无法使用这样的ipython扩展来有效地将内容导入用户环境。 The extension is running, but imports made in the extension file are not imported into the notebook kernel (which makes sense). 扩展正在运行,但扩展文件中的导入不会导入到笔记本内核中(这是有意义的)。 I tried using the interactive shell object in combination with user_expressions, but didn't work either. 我尝试将交互式shell对象与user_expressions结合使用,但也没有用。

My question is: What is the easiest way to automate this standard cell, if an extension is the way to go, how can i do an import (and the relevant magic functions) from such an extension? 我的问题是:自动化这个标准单元的最简单方法是什么,如果要进行扩展,我该如何从这样的扩展中进行导入(以及相关的魔术功能)?

fixed it: 修复:

Probably a bit of a contrived, but it works so I'm happy. 可能有点做作,但它的确有效,所以我很高兴。 Leaving this for future people who want to make their lives easier. 将此留给未来希望让生活更轻松的人们。

Solution: 解:

Make a ipython extension by following these instructions by following these instructions . 按照这些说明操作,按照这些说明进行ipython扩展。

In the .py file for this extension I wrote the following code: 在此扩展的.py文件中,我编写了以下代码:

def instructions():
    inst = """
    import pandas as pd
    ... other imports

    sys.path.append('../..')
    ... more imports

    """
    return inst


def load_ipython_extension(ipython):
    compiled_file = "prep_log.py"
    code = compile(instructions(), compiled_file, 'exec')
    ipython.run_code(code)
    ipython.run_line_magic("matplotlib", "inline")
    ipython.run_line_magic("load_ext", "autoreload")
    ipython.run_line_magic("autoreload", "2")

Now i just have the line %load_ext prep on the top of my notebook and I'm ready to go :). 现在我只是在我的笔记本顶部有%load_ext准备行,我准备好了:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM