tags:

views:

88

answers:

3

I've written a library in python and I want it to reside in a common location on the file system.

From my script, I just want to do:

>>> import mylib

Now I understand that in order to do this, I can do this:

>>> import sys
>>> sys.path.append(r'C:\MyFolder\MySubFolder')
>>> import mylib

But I don't want to have to do that every time.

The question is: How do I add a folder to python's sys.path permanently? I would imagine that it would be an environment variable, but I can't find it.

It seems like it should be easy, but I can't find out how to do it.

+4  A: 

The PYTHONPATH environment variable will do it.

Nathon
Perfect. That's what I was looking for.
Stargazer712
+2  A: 

Deducing from the path you provided in your example here's a tutorial for setting the PYTHONPATH variable in Windows: http://docs.python.org/using/windows.html#excursus-setting-environment-variables

Uku Loskit
Also perfect...not sure which to give the check to...
Stargazer712
A: 

Another possibility is to alter the sys.path in your sitecustomize.py, a script that is loaded as Python startup time. (It can be put anywhere on your existing path, and can do any setup tasks you like; I use it to set up tab completion with readline too.)

The site module offers a method that takes care of adding to sys.path without duplicates and with .pth files:

import site
site.addsitedir(r'C:\MyFolder\MySubFolder')
bobince
If adding a file to the current path were an option, why would I even bother trying to change the path at all? And even worse, what could possibly make me want to add that line to every single python script that I write? Sorry bud...not very elegant.
Stargazer712
@Stargazer712: Er... `sitecustomize.py` is run automatically by Python. You don't have to add a line to every Python script. That's the whole point.
bobince
@bobince, perhaps it is from an unspoken requirement that this library installed using a typical installer, and modifying an environment variable is far easier (and more transaction-like) than editing a file.
Stargazer712
Ah, if that's the case: drop a .pth file in the Python installation's `site-packages` folder containing the path to the outside folder. This is more reliable than frobbing the PYTHONPATH or sitecustomize. (If you need an outside directory at all... for a ‘typical’ library, normally distutils/setuptools would take care of dropping it in the appropriate place.)
bobince