18

I want to put couple of cells with commands I need in almost every new notebook in every new notebook I create.

For example when I create a new notebook it should put a

%matplotlib inline
import matplotlib.pyplot as plt

in a cell by default but not execute it. How could I set something like that up?

user9886
  • 301
  • 3
  • 11

3 Answers3

12

This will work for both terminal based IPython shell and Browser based Notebook:

  • Navigate to ~/.ipython/profile_default
  • Create a folder called startup if it’s not already there
  • Add a new Python file called start.py
  • Put your favorite imports (and custom functions may be) in this file
  • Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!

Here is my sample for start.py: enter image description here

Another Source

Umair Qadir
  • 384
  • 3
  • 7
4

To define set of commands on default startup, you need to add the commands in the templete ipy_user_conf.py file in your ~/.ipython directory.
This module is imported during IPython startup. So you can easily do : import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace etc.
Here is the sample 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()

For more details, please refer the link : Customization of IPython.

I hope this is what you wanted to know.

Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101
  • 2
    Thanks. Your answer seems to be not quite what I was looking for, though. The documentation linked is for a very old version of ipython and explains how to set up commands that are executed when starting ipython. What I am looking for, however, is a way to add a custom initialisation cell to every newly created notebook. This might seem equivalent, but it is not if, for example, you want to share notebooks. – user9886 Feb 25 '15 at 11:27
1

JupyterLab

In a comment to one of the other answers, the OP pointed out the need to insert the actual code instead of having it load in the background. One way is to create a text keyboard shortcut by going to Settings -> Advanced settings editor -> JSON settings Editor and adding the following under User Preferences:

{
    "shortcuts": [
        {
            "command": "apputils:run-first-enabled",
            "selector": "body",
            "keys": ["Alt I"],
            "args": {
                "commands": [
                    "console:replace-selection",
                    "fileeditor:replace-selection",
                    "notebook:replace-selection",
                ],
                "args": {"text": "import pandas as pd\nimport altair as alt\n\n"}
            }
        }
    ]
}

This will insert the following snippet each time you press Alt + i in the notebook:

import pandas as pd
import altair as alt


# <-- Cursor placed here

More on text shortcuts in jupyterlab

IPython console

If you are interested in automatically importing commonly used libraries in the IPython console only so that they are there for interactive use, but not in the notebook to avoid issues with sharing notebooks lacking some imports, you can launch IPython like so (and set up an alias to not have to type this each time):

ipython -c "import pandas as pd; import numpy as np" -i

(This was what I was looking for when I originally found this question)

joelostblom
  • 43,590
  • 17
  • 150
  • 159