如何在iPython笔记本中设置默认启动命令?

use*_*886 10 ipython-notebook ipython-magic jupyter-notebook

我希望在我创建的每个新笔记本中几乎每个新笔记本中都放置几个单元格.

例如,当我创建一个新笔记本时,它应该放一个

%matplotlib inline
import matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

默认情况下在单元格中但不执行它.我怎么能设置这样的东西?

小智 5

这适用于基于终端的 IPython shell 和基于浏览器的 Notebook:

  • 导航 ~/.ipython/profile_default
  • 创建一个文件夹,startup如果它不存在则调用
  • 添加一个名为的新 Python 文件 start.py
  • 把你最喜欢的importscustom functions可能是)放在这个文件中
  • 启动 IPython 或 Jupyter Notebook,每次都会自动加载您喜欢的库!

这是我的示例start.py在此处输入图片说明

另一个来源


Nis*_*yal 4

要在默认启动时定义命令集,您需要在~/.ipython目录中的 templatete ipy_user_conf.py文件中添加命令。 该模块在 IPython 启动期间导入。因此,您可以轻松地执行以下操作:导入模块、配置扩展、更改选项、定义魔术命令、将变量和函数放入 IPython 命名空间等。 这是示例 ipy_user_conf.py :

# Most of your config files and extensions will probably start
# with this import

import IPython.ipapi
ip = IPython.ipapi.get()

# You probably want to uncomment this if you did %upgrade -nolegacy
# import ipy_defaults

import os

def main():

    #ip.dbg.debugmode = True
    ip.dbg.debug_stack()

    # uncomment if you want to get ipython -p sh behaviour
    # without having to use command line switches
    import ipy_profile_sh
    import jobctrl

    # Configure your favourite editor?
    # Good idea e.g. for %edit os.path.isfile

    #import ipy_editors

    # Choose one of these:

    #ipy_editors.scite()
    #ipy_editors.scite('c:/opt/scite/scite.exe')
    #ipy_editors.komodo()
    #ipy_editors.idle()
    # ... or many others, try 'ipy_editors??' after import to see them

    # Or roll your own:
    #ipy_editors.install_editor("c:/opt/jed +$line $file")


    o = ip.options
    # An example on how to set options
    #o.autocall = 1
    o.system_verbose = 0

    #import_all("os sys")
    #execf('~/_ipython/ns.py')


    # -- prompt
    # A different, more compact set of prompts from the default ones, that
    # always show your current location in the filesystem:

    #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
    #o.prompt_in2 = r'.\D: '
    #o.prompt_out = r'[\#] '

    # Try one of these color settings if you can't read the text easily
    # autoexec is a list of IPython commands to execute on startup
    #o.autoexec.append('%colors LightBG')
    #o.autoexec.append('%colors NoColor')
    o.autoexec.append('%colors Linux')


# some config helper functions you can use
def import_all(modules):
    """ Usage: import_all("os sys") """
    for m in modules.split():
        ip.ex("from %s import *" % m)

def execf(fname):
    """ Execute a file in user namespace """
    ip.ex('execfile("%s")' % os.path.expanduser(fname))

main()
Run Code Online (Sandbox Code Playgroud)

更多详情请参考链接: IPython的定制

我希望这是您想知道的。

  • 谢谢。不过,您的答案似乎并不完全是我想要的。链接的文档适用于 ipython 的非常旧的版本,并解释了如何设置启动 ipython 时执行的命令。然而,我正在寻找一种向每个新创建的笔记本添加自定义初始化单元的方法。这看起来可能是等效的,但如果您想共享笔记本,则情况并非如此。 (2认同)