Preload some libraries and scripts in python

How do I preload some libraries and scripts in python before I call the python command? Is there something like a .bashrc file to pre-define some functions / variables before starting the shell terminal?



source to share

3 answers

Create a file "" and add import lines for all your modules.

import math
import anothermodule
import anotherothermodule


Then set the "PYTHONSTARTUP" environment variable and set it to "/path/to/".

Now when you run python on the command line, it will load your modules first.



How about this:

python -i -c "import math"


And you can put this in a bash file like

#! /bin/bash

python -i -c "import math"


Then you can install whatever you want.



I sometimes needed to run python with a bunch of statistics / math stuff to load (numpy, matplotlib, etc.), but otherwise just plain python without the overhead of loading modules I wasn't going to use.

I am using ubuntu linux, so I created a python script

with the following:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl


and added an alias to mine ~/.bashrc


alias pym='PYTHONSTARTUP=/home/$USER/path/to/script/ python'


so when I want regular python to run python

, and when I want all math stuff to run pym


hope this helps. based on Tony Blundell's answer.



All Articles