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?

Thank.

+3


source to share


3 answers


Create a file "my_imports.py" 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/my_imports.py".

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

+5


source


How about this:

python -i -c "import math"

      

And you can put this in a bash file like b.sh



#! /bin/bash

python -i -c "import math"

      

Then you can install whatever you want.

0


source


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 python-preload.py

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-preload.py 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.

0


source







All Articles