[Tutor] Setting PYTHONPATH and other env vars dynamically

Alan Gauld alan.gauld at btinternet.com
Wed Aug 19 11:30:11 CEST 2009


"Jramak" <jramak345 at gmail.com> wrote

> We have developed three custom applications in Python. Each one of
> these applications needs a different PYTHONPATH, in addition to
> different environment variables to work.

Environment variables should control the users (or oprocess) environment
and as such should really be fairly static, you could cause real problems
if you start changing the users environment dynamically because that might
affect how other applications run that also rely on PYTHONPATH or whatever.

Now, its true that each process gets a copy of the shell environment
so changing it within the process shouldn't affect the external environment
but to me it is still the wrong way to go about it. At the very least it 
means
your environment variables no longer accurately reflect the users 
environment
so you might get surprises if you try and launch a shell process or batch 
job
which picks up the original environment!

In this case I'd much rather change sys.path. That is a Python list and 
much
easier to add items at startup rather than mess with the environment.

> the environment variables for each application, what would be the best
> way to set PYTHONPATH and other environment variables for a specific
> application?

Use config values in an ini file and set global variables in your program
at startup, and for paths use sys.path. (So far as I can tell thats what
Python does with PYTHONPATYH - it loads the values into sys.path
at startup...)

> We only run one application at a time, not all of them.
> We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash
> script that sets the environment variables on the application start-up
> way to go?

That is only slightly better since the environment no longer reflects the
users normal environment. It does mean the bash script could launch
multiple programs etc andd they would at lest share a common environment
but in your case I don't think its the best solution.

> Any ideas? I was not aware of site.py until a co-worker bandied it
> about - he says site.py is better than PYTHONPATH.

They do different things! site.py is about customising Python on that
site - which may be a shared installation - and environment variables
are about describing a users environment, and can be different for
each user. Now, there is an overlap, but Pythonpath is not one of them
since multiple users can share a site! (site.py is probably better
than setting a System wide PYTHONPATH though....) But again
site.py applies to every application you should not start modifying
it with application specific startup code - yuck! It could soon turn
into spaghetti and seriously slow down startup of everything.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list