146

I find myself typing import numpy as np almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?

nachocab
  • 13,328
  • 21
  • 91
  • 149
user545424
  • 15,713
  • 11
  • 56
  • 70

9 Answers9

94

For ipython, there are two ways to achieve this. Both involve ipython's configuration directory which is located in ~/.ipython.

  1. Create a custom ipython profile.
  2. Or you can add a startup file to ~/.ipython/profile_default/startup/

For simplicity, I'd use option 2. All you have to do is place a .py or .ipy file in the ~/.ipython/profile_default/startup directory and it will automatically be executed. So you could simple place import numpy as np in a simple file and you'll have np in the namespace of your ipython prompt.

Option 2 will actually work with a custom profile, but using a custom profile will allow you to change the startup requirements and other configuration based on a particular case. However, if you'd always like np to be available to you then by all means put it in the startup directory.

For more information on ipython configuration. The docs have a much more complete explanation.

Honest Abe
  • 8,430
  • 4
  • 49
  • 64
ravenac95
  • 3,557
  • 1
  • 20
  • 21
  • 2
    In Ubuntu 14.04 the directory actually is: `~/.config/ipython/profile_default/startup/` and not `~/.ipython/profile_default/startup/` – Peter Jan 22 '16 at 12:21
  • 1
    Unfortunately, option 2 above doesn't allow tab completion. – user1717828 Feb 26 '18 at 13:35
  • In Ubuntu 20.04 the directory actually is: `~/.ipython/profile_default/startup/` and not `~/.config/ipython/profile_default/startup/` – ramwin Oct 29 '22 at 01:02
87

Use the environment variable PYTHONSTARTUP. From the official documentation:

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session.

So, just create a python script with the import statement and point the environment variable to it. Having said that, remember that 'Explicit is always better than implicit', so don't rely on this behavior for production scripts.

For Ipython, see this tutorial on how to make a ipython_config file

Honest Abe
  • 8,430
  • 4
  • 49
  • 64
Dhara
  • 6,587
  • 2
  • 31
  • 46
28

I use a ~/.startup.py file like this:

# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")

pp = pprint.pprint

Then define PYTHONSTARTUP=~/.startup.py, and Python will use it when starting a shell.

The print statements are there so when I start the shell, I get a reminder that it's in effect, and what has been imported already. The pp shortcut is really handy too...

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Didn't work for me on Linux. Do I have to tell Python to look in my home directory or something? – Seanny123 Jun 25 '15 at 20:01
  • oops: forgot an important step: I've added it: define PYTHONSTARTUP – Ned Batchelder Jun 25 '15 at 23:58
  • I never know when the `~` as a substitute for `$HOME` works or not, but instead of this relative path I had to use a absolute path on MacOS, fish and python3. – rien333 Dec 11 '17 at 21:00
  • [`pprint.pp()`](https://docs.python.org/3/library/pprint.html#pprint.pp) now exists, so you might want to change that shortcut to avoid confusion. – wjandrea Mar 07 '22 at 23:04
  • Where should I add the `PYTHONSTARTUP=~/.startup.py`? And shouldn't we use `"` for the path? (`PYTHONSTARTUP="~/.startup.py"`) – Shayan Dec 31 '22 at 09:43
8

While creating a custom startup script like ravenac95 suggests is the best general answer for most cases, it won't work in circumstances where you want to use a from __future__ import X. If you sometimes work in Python 2.x but want to use modern division, there is only one way to do this. Once you create a profile, edit the profile_default (For Ubuntu this is located in ~/.ipython/profile_default) and add something like the following to the bottom:

c.InteractiveShellApp.exec_lines = [
    'from __future__ import division, print_function',
    'import numpy as np',
    'import matplotlib.pyplot as plt',
    ]
Community
  • 1
  • 1
Teque5
  • 424
  • 7
  • 7
7

As a simpler alternative to the accepted answer, on linux:

just define an alias, e.g. put alias pynp='python -i -c"import numpy as np"' in your ~/.bash_aliases file. You can then invoke python+numpy with pynp, and you can still use just python with python. Python scripts' behaviour is left untouched.

blue
  • 2,683
  • 19
  • 29
  • 2
    `PYTHONSTARTUP` is only invoked on **interactive** mode, so python scripts‘ behaviour is kept untouched anyways. An alias could also be created with a file reference: `alias pynp='PYTHONSTARTUP="~/.startup.py" python'` – F.Raab Jan 09 '19 at 16:43
4

You can create a normal python script as import_numpy.py or anything you like

#!/bin/env python3
import numpy as np

then launch it with -i flag.

python -i import_numpy.py

Way like this will give you flexibility to choose only modules you want for different projects.

Raja G
  • 5,973
  • 14
  • 49
  • 82
1

As ravenac95 mentioned in his answer, you can either create a custom profile or modify the default profile. This answer is quick view of Linux commands needed to import numpy as np automatically.

If you want to use a custom profile called numpy, run:

ipython profile create numpy
echo 'import numpy as np' >> $(ipython locate profile numpy)/startup/00_imports.py
ipython --profile=numpy

Or if you want to modify the default profile to always import numpy:

echo 'import numpy as np' >> $(ipython locate profile default)/startup/00_imports.py
ipython

Check out the IPython config tutorial to read more in depth about configuring profiles. See .ipython/profile_default/startup/README to understand how the startup directory works.

Community
  • 1
  • 1
anishpatel
  • 1,472
  • 1
  • 16
  • 23
1

My default ipython invocation is

ipython --pylab --nosep --InteractiveShellApp.pylab_import_all=False

--pylab has been a ipython option for some time. It imports numpy and (parts of) matplotlib. I've added the --Inter... option so it does not use the * import, since I prefer to use the explicit np.....

This can be a shortcut, alias or script.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

I created a little script to get ipython initialized with the code you want.

  • Create a start.ipy file at your project root folder.
  • Edit the created file with all the things you need to get into ipython.
  • ipython profile create <your_profile_name>. Tip, do not add the word "profile" to the name because ipython already includes it.
  • cp start.ipy ~/.ipython/profile_<your_profile_name>/startup/start.ipy
  • Run ipython --profile=<your_profile_name> everytime you need everything loaded in ipython.

With this solution, you don't need to set any env variable up. You will need to copy the start.ipy file to the ipython folder every time you modify it, though.

letoss
  • 31
  • 3