Automatically import modules when entering the python or ipython interpreter
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.
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...
For ipython, there are two ways to achieve this. Both involve ipython's configuration directory which is located in ~/.ipython
.
- Create a custom ipython profile.
- 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.
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