Lessons learnt: Python and importing

This will probably not be something you will do every day, but some day you might need to import a module from an altogether different directory not on the python path. Let’s for instance say that you have a script in your home folder:


This script needs to import another module, and, as in my case, you are only given the file system path to the directory in which you can find said module. What to do?


The solution is rather simple. some_script.py will need to import sys, in order to get a hold of the sys.path variable, to which we can append the path.

import sys
import some_module

Tah-dah. Once the script has been executed and dies, the sys.path is restored, so no extra fiddling needed. The one gotcha I encountered, which made this problem take way much longer than it should have:

I was wrapping this code up in a function, and that made the import local to that function, and not visible in the rest of the script, so binding functions/variables from the imported module to local ditos is advised, and then moving these around instead.

What kind of ugly beast of a script I needed something as convoluted as this for? A script which tries to verify that a piece of installed software has been installed correctly, and at the correct place with respect to other software, which I from the onset cannot know where it exists (this is for Vox Anonymus, and I simply needed to check that the Django site specific settings file had been correctly updated and could find Vox Anon.

Tags: , , , , ,

Comments are closed.