[Tutor] Setting PYTHONPATH and other env vars dynamically

Douglas Philips dgou at mac.com
Wed Aug 19 03:21:18 CEST 2009


On 2009 Aug 18, at 7:57 PM, Jramak wrote:
> Hello
> 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. Instead of manually setting
> the environment variables for each application, what would be the best
> way to set PYTHONPATH and other environment variables for a specific
> application? 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?
>
> Any ideas? I was not aware of site.py until a co-worker bandied it
> about - he says site.py is better than PYTHONPATH.

Ok, well, if you are on Windows and your talking about bash scripts,  
it sounds like you might be using cygwin? Typically "scripts" on  
Windows are .BAT files, so I am not sure what you're referring to here.
I think you have five-ish general options:

a) set variables by hand. run program(s) by hand. (not very much fun,  
and possibly error prone.)

b) create scripts (bash or .BAT or whatever, depending on your  
situation) that set the variables and runs your program(s).

c) install whatever your programs need under the site-packages  
directory of your python install.
This assumes that all the packages your programs need have unique  
names. I can't tell from your description if they are different  
pacakges or if they might just be different versions of the same  
package. If they are just different versions of the same package,  
probably this option wouldn't work, it all depends on the specific  
files. It also depends on where you have Python 2.5.2. and Python  
2.4.1 installed and if you use them at the same time. This option  
still requires another option for setting the other environment  
variables.

d) Set up your environments in each of your main programs. Here is the  
boilerplate you might use:
# This needs to be at the top of the program after the module doc  
string (if any) and before any other statements or imports:

import sys
sys.path.append("dir1/dir2")  # Add dir1/dir2 to your Python search  
path. Can be absolute path or relative.
sys.path.append("dir3/dir4")
# ...

import os
os.environ['MYVARIABLE'] = 'MyVALUE'
os.environ['ANOTHERONE'] = 'someothervalue'
# ...

This has the nice property that everything is self contained. But that  
also can be a downside if the values need to be changed by someone  
else, they'd have to go and edit .py files.

e) option d and a (seems unlikely), option d and b, option d and c.  
Depending on what you variables are, and how often they change, it  
might make sense to put some of them (Python path or environment) into  
the programs, and the rest in scripts.

Hope this helps,
	--Doug



More information about the Tutor mailing list