1

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.

phil0stine
  • 303
  • 1
  • 13
  • Have you tried this : http://stackoverflow.com/a/10859845/1134940 – Abid Rahman K Jul 28 '12 at 06:04
  • Thanks I imagine the same technique will work for me even though I am working in Linux. The trick is that I might not want to overwrite the older version for now, so I wanted to be able to toggle within a script. `imp` did what I wanted but when I want to migrate for good I will try your technique – phil0stine Jul 30 '12 at 01:16

2 Answers2

1

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

ashastral
  • 2,818
  • 1
  • 21
  • 32
0

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")
fsong
  • 656
  • 5
  • 8
  • Probably you'll need to put "path/to/cvs2" before the "/usr/local" in sys.path. – mhawke Jul 25 '12 at 02:28
  • Thanks, unfortunately I tried to do both `sys.path.append(pathname)` and `sys.path.insert(0,pathname)` with no luck. This is why I am so puzzled as to _what_ exactly the problem is, and why this solution doesn't work. – phil0stine Jul 25 '12 at 02:50