How do I put a Python module in a folder other than my script?


I am trying to run a script in Python ( v2.4 and v2.7 ) and created a module with some methods. Unfortunately this module needs to be in a separate folder.

At Python documentation and up to here in Stack Overflow I found numerous post talking to add to each folder in my project.

My problem is that my script stays in one structure and my module stays in another one. My situation is this:


The part that I'm calling these modules in my script is:


# -*- coding: utf-8 -*-

import sys  
import datetime  

from pasta3.modulo1 import Mod1  
from pasta3.modulo2 import Mod2 

The error :

$ ./   
Traceback (most recent call last):  
     File "./", line 9, in <module> from pasta3.modulo1 import Mod1  
ImportError: No module named pasta3.modulo1

I can not use sys.path.append("../modules/python/") because in Python 2.4 it is not recognized.

How to proceed in this case?

asked by anonymous 25.04.2014 / 22:11

4 answers


In Python 2.x , you can use the Imp :


This module provides an interface to the mechanisms used to implement   the import statement.

Use the functions find_module and load_module .

  • find_module : Will search for the module by name, if the search is successful, the return value is a tuple of 3 elements containing the file, path, and description.

  • load_module : Will import the module, if the module has already been imported, it will only be reloaded - equivalent to reload . Return is an object that points to the module, otherwise an exception ImportError is released.


import imp

arquivo, caminho, descricao = imp.find_module('Modulo1', ['/foo/bar/baz/'])

modulo1 = imp.load_module('Modulo1', arquivo, caminho, descricao)


Starting with the +3.4 version of Python the module Imp became obsolete , alternatively you can use the importlib (is available since Python 2.7 ).

27.04.2014 / 17:35

Try to return a directory and indicate the path, for example:

from ..pasta3.modulo1 import Mod1
25.04.2014 / 22:28

Set the environment variable PYTHONPATH and include ( append if already exists) the pasta3 directory:

export PYTHONPATH = /pasta2/modules/python/pasta3

In any case, you can use the full path for pasta3 instead of relative.

26.04.2014 / 20:22

Why not use a symlink for pasta2 within pasta1 :

$ ln -s ./pasta2 ./pasta1/pasta2
27.04.2014 / 09:51