MyRaspberryAndMe

Tinkering with Raspberry (and other things)

Quick Tip: Adding a directory to Python’s module search path

2 Comments

Over time I have written some Python modules/classes that I am using in more than one little project. As these are single files mostly, I did not bother about writing “real” modules with “setup.py” and all that stuff. I do not want to install these files in Python’s default library directory, either.

So I did what one should never ever do 🙂 I copied the files into the project directories as needed. This quickly gets out of hand if you are doing some updates to one of the classes. In order to get some robust structure into my workplace on the Raspberry Pi I did some research and reading about installing Python modules and came up with the most simple solution I can think of: adding my own directory to Python’s search path.

In the Python documentation everything I did can be found, of course. As I did miss it during several reads, I am posting my way of doing it here. To remind me and to, hopefully, help others.

First, a directory to put all the modules to be reused into needs to be created:

mkdir some_Directory_Name

Now we need to add an environment variable that gets set when you log in. Go to your home directory and edit the file “.profile”:

cd
nano .profile

At the end of the file add the following lines:

if [ -d "$HOME/Workplace/Python/MyModules" ] ; then
    export PYTHONPATH="$HOME/some_Directory_Name"
fi

That’s pretty all there is to do. The next time you log in the variable PYTHONPATH is set and used by Python. The if-statement checks for the existence of the given directory. The environment variable will only be created if the directory exists.

You can check this. Do not log out yet, but start Python and do the following (screenshot for better readability:

Bildschirmfoto 2013-12-04 um 14.57.10

This gives you the directories where Python looks for files when you are using the import-statement. Now to have our changes take effect, we could log out and in again, or we re-read the .profile with:

. ~/.profile

There needs to be a space between the first dot and the tilde character. If you are now starting Python again and do the exact same thing you should see your path somewhere in the output from sys.path:

Bildschirmfoto 2013-12-04 um 14.57.59

I have highlighted my personal search path in the above picture.

That’s all for this quick tip.

Advertisements

2 thoughts on “Quick Tip: Adding a directory to Python’s module search path

  1. Reblogged this on n93.

  2. Pingback: Quick Tip: crontab and python | MyRaspberryAndMe