4

I think other may ask this before but I cannot find it. My question is, I have these statements in my .ipython/ipy_user_conf.py:

ip.ex('import matplotlib as mat')
ip.ex('import matplotlib.pyplot as plt')
ip.ex('import numpy as np')
ip.ex('import pupynere as pu')
ip.ex('import g')
ip.ex('import bsite')
ip.ex('import csvf')
ip.ex('import pandas as pa')
ip.ex('import pickle as pk')
ip.ex('import mathex as mathex')
ip.ex('import os as os')
ip.ex('import re as re')
ip.ex('import scipy as sp')
ip.ex('import mpl_toolkits.basemap as bmp')
ip.ex('from mpl_toolkits.basemap import cm')

Then If I use python in ipython shell, these modules will be loaded directly when I start ipython, but if I have a python script, eg., ba_plot.py used to make some plots. I debugged the script by an interactive way in the ipython, but then I want to run it within the shell terminal, like:

chaoyue@chaoyue-Aspire-4750:~$  python ba_plot.py

but before this, each time I need to copy at the beginning of ba_plot.py file the following again:

import matplotlib as mat
import matplotlib.pyplot as plt
import numpy as np
import pupynere as pu
import g
import bsite
import csvf
import pandas as pa
import pickle as pk
import mathex as mathex
import os as os
import re as re
import scipy as sp
import mpl_toolkits.basemap as bmp
from mpl_toolkits.basemap import cm

Because otherwise it will complain it cannot find the module. So, is there anyway that I can avoid do this by including some header file at the beginning of my python script while in the header file all these modules are imported? By this way, I need only to add on line at the beginning of my python script.

gecco
  • 17,969
  • 11
  • 51
  • 68
wiswit
  • 5,599
  • 7
  • 30
  • 32
  • *there should be newline symbol between but the web cannot display the `'\n'` properly*: You can just select the lines and click the *format as code* button above the edit field. – Björn Pollex Nov 24 '11 at 10:38

2 Answers2

3

It's bad practice to have a script which depends on an external startup script to make it work. Doing these imports is how you should do it.

You could simplify it if you regularly import a fairly large set of things by centralising your imports in a file (call it common_imports.py, for example), and then importing all from that (from common_imports import *). That then becomes only one line to put in. I would still prefer to see explicit imports, however.

(Another note: in import os as os, the as os is entirely superfluous.)

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
1

You need to modify site.py. This script is run every time the Python program is run. For me, it lives in /usr/lib/python2.7/site.py

As Chris Morgan says, this is terribly bad practice and I strongly recommend you avoid it.

Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38
  • Hi, thanks for this good discussions. really helpful and give me a sense that I need not to struggle alone in the way. – wiswit Nov 28 '11 at 10:23