phil0stine
phil0stine

Reputation: 303

python wont load module unless started in a specific directory

I just pulled the latest version of opencv from source, and unfortunately for the moment I must have 2 different versions on one machine.

So I have the default location /usr/local/... for the older version, and a custom location for the newer version.

My issue is that if I open a python terminal and try to import cv2, I can only get the new version to load if I start in the opencv/lib directory of the new version.

I want to be able to toggle which version of opencv I use, ideally it would be in the python script itself.

I expected to be able to set either LD_LIBRARY_PATH or PYTHONPATH or both in the terminal, or change the environment variables using os.environ, but had no success.

First, I don't understand why I have to be in the lib directory to get the new version to load, and second I don't see why I cannot dynamically change where python looks to import the module using environment variables.

Any help is appreciated.

Upvotes: 1

Views: 395

Answers (2)

ashastral
ashastral

Reputation: 2848

You can use the imp module to import from a specified path.

import imp
fp, pathname, description = imp.find_module('cv2', ['/path/to/opencv/'])
cv2 = imp.load_module('cv2', fp, pathname, description)

http://docs.python.org/library/imp.html

Upvotes: 1

fsong
fsong

Reputation: 666

Use the sys module. After the Python interpreter is started, you can modify the module path via sys.path which is actually just a list.

import sys
sys.path.append("/path/to/cv2")

Upvotes: 0

Related Questions