on and off over the years I keep trying to get `pydoc` to work from inside a Django project. it always fails.

(virtualenv) jcomeau@aspire:~/rentacoder/jmol$ (cd molecules/ && python -m pydoc viewer.views) problem in viewer.views - ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

so then, following this, I do:

(virtualenv) jcomeau@aspire:~/rentacoder/jmol$ (cd molecules/ && DJANGO_SETTINGS_MODULE=molecules.settings python -m pydoc viewer.views)
problem in viewer.views - AppRegistryNotReady: Apps aren't loaded yet.

googling around, I found out I could call django.setup() to fix that, but figured that could cause unwanted side effects in normal use. so then I searched for how to know the name of the importer, and none of these answers worked either. but somewhere along the line I got a pointer to sys.modules and this turned out to be the winner. I added:

import sys
importer = sys.modules['__main__'].__spec__
if importer.name == 'pydoc':
    import django

and now (virtualenv) jcomeau@aspire:~/rentacoder/jmol$ (cd molecules && DJANGO_SETTINGS_MODULE=molecules.settings python -m pydoc viewer.views) shows me the pydoc!

Back to blog or home page

last updated 2016-10-19 16:13:51. served from tektonic