15

I am running an Ubuntu 14.4 and I have installed a python virtual environment. Then I pip installed several python libraries (gdal, lxml, psycopg2 etc.)

Also in my system I have the module for QGIS. So when I type python then I can import this module as:

import qgis.core 

But when I try to do the same through my virtualenv I get an error: module not found.

When I created the virtualenv I did with the option:

virtualenv --no-site-packages env 

Which restricts my env from the system's env. The question is how to access QGIS module in my virtualenv?

2
  • 1
    This might help. Have not tried it myself, yet. Commented Oct 10, 2016 at 1:24
  • 1
    This might also help. Have not tried it myself. Commented Nov 24, 2016 at 11:05

1 Answer 1

2

After create and activate your virtualenv :

virtualenv --no-site-packages env source env/bin/activate pip install [your libs] 

You have to defined the PYTHONPATH environnement variable to your QGIS's python installation path.

please change [qgispath] to your qgis's path :

export PYTHONPATH=/[qgispath]/share/qgis/python 

it will also be necessary to set LD_LIBRARY_PATH

export LD_LIBRARY_PATH=/[qgispath]/lib 

to prevent this error

>>> import qgis.core ImportError: libqgis_core.so.1.5.0: cannot open shared object file: No such file or directory 

Your pythonpath is set only for the virtualenv, and for your session. If you want to set it automatically under this virtualenv, you can create a file under env/lib/python2.7/site-packages with a .pth file.

The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. (Because the new paths are appended to sys.path, modules in the added directories will not override standard modules. This means you can’t use this mechanism for installing fixed versions of standard modules.) source

to create and populate the file use a command like that :

cat > [yourVirtualEnv]/lib/python2.7/site-packages/qgispythonpath.pth << /[qgispath]/share/qgis/python 

Found in Python Qgis cookbook, and a related answer set pythonpath

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.