Make packages installed in virtualenv visibile with sphinx

I use sphinx

to document my software. and I am using virtualenv

to install. now some packages are installed only in a virtual environment, and the sphinx does not see them.

I have this code in mine


# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
p = os.path.abspath('..')
sys.path.insert(0, p)
if 'VIRTUAL_ENV' in os.environ:
    q = os.sep.join([os.environ['VIRTUAL_ENV'],
                     'lib', 'python2.7', 'site-packages'])
    sys.path.insert(0, q)
    p = p + ":" + q

os.environ['PYTHONPATH'] = p


but if I do make html

, I get warnings like this:

/home/mario/Local/github/Bauble/bauble.classic/doc/api.rst:358: WARNING: autodoc: failed to import class u'TagItemGUI' from module u'bauble.plugins.tag'; the following exception was raised:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/sphinx/ext/", line 385, in import_object
  File "/home/mario/Local/github/Bauble/bauble.classic/bauble/plugins/tag/", line 30, in <module>
    from sqlalchemy import *
ImportError: No module named sqlalchemy


my $VIRTUAL_ENV/lib/python2.7/site-packages

contains SQLAlchemy-1.0.4-py2.7-linux-x86_64.egg


definitely related to the question Sphinx autodoc dies from a 3rd party package ImportError , but the description of the procedure I chose is in the broken link.


source to share

1 answer

The problem is that the packages are not directly included in the virtualenv site-packages

dir, you will need to provide the full path to be able to import the package from there. I am using the following hack:

if 'VIRTUAL_ENV' in os.environ:
    site_packages_glob = os.sep.join([
        'lib', 'python2.7', 'site-packages', 'projectname-*py2.7.egg'])
    site_packages = glob.glob(site_packages_glob)[-1]
    sys.path.insert(0, site_packages)


Where projectname

is the name of the python module that I would like to import.

Please note that this is error prone, especially if you have multiple versions of the module, but so far this works for me.



All Articles