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

7

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 __init__.py 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:

pasta1/
   script.py
pasta2/
   modules/
      python/
          pasta3/
              \__init\__.py
               modulo1.py
               modulo2.py

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

#!/usr/bin/python

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

import sys  
import datetime  

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

The error :

$ ./script.py   
Traceback (most recent call last):  
     File "./script.py", 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

3

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.

Example:

import imp

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

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

modulo1.funcao1()

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
4

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

script.py

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

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
1

Why not use a symlink for pasta2 within pasta1 :

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