从conf.py安装扩展

时间:2014-12-26 03:18:46

标签: python python-sphinx importerror easy-install

我尝试构建文档,并使用custom sphinx extension,但默认情况下未安装此扩展程序 - 因此我通过conf.py提供此文件,使用此文件:

try:
    import sphinxjp.themes
except ImportError:
    from setuptools.command import easy_install
    easy_install.main( ["-U","sphinxjp.themes.basicstrap"] )
    import sphinxjp.themes

extensions += ['sphinxjp.themes.basicstrap']
html_theme = 'basicstrap'

html_theme_options = {
  'bootstrap_version': '3',
  'noresponsive': False,
  'inner_theme': True,
  'inner_theme_name': 'bootswatch-yeti',
}

但问题如下:

  1. 如果找不到扩展程序,则安装扩展程序;如果存在,则跳过该程序包。
  2. 但是在这里,如果它不存在,python将安装它,并继续执行文件,就好像它没有安装
  3. 然后我再次运行该文件,以便python可以跳过安装过程并构建文档。
  4. 如何在安装后立即强制python加载扩展名?

    我收到此错误:

    Running Sphinx v1.3b2
    Searching for sphinxjp.themes.basicstrap
    Reading https://pypi.python.org/simple/sphinxjp.themes.basicstrap/
    Best match: sphinxjp.themes.basicstrap 0.4.1
    Downloading https://pypi.python.org/packages/source/s/sphinxjp.themes.basicstrap
    /sphinxjp.themes.basicstrap-0.4.1.tar.gz#md5=bac7d878391a3dfd663b51e2311d5795
    Processing sphinxjp.themes.basicstrap-0.4.1.tar.gz
    Writing c:\users\abdelo~1\appdata\local\temp\easy_install-ndzj8s\sphinxjp.themes
    .basicstrap-0.4.1\setup.cfg
    Running sphinxjp.themes.basicstrap-0.4.1\setup.py -q bdist_egg --dist-dir c:\use
    rs\abdelo~1\appdata\local\temp\easy_install-ndzj8s\sphinxjp.themes.basicstrap-0.
    4.1\egg-dist-tmp-pdyuqk
    Adding sphinxjp.themes.basicstrap 0.4.1 to easy-install.pth file
    
    Installed c:\python27\lib\site-packages\sphinxjp.themes.basicstrap-0.4.1-py2.7.e
    gg
    Processing dependencies for sphinxjp.themes.basicstrap
    Finished processing dependencies for sphinxjp.themes.basicstrap
    
    Exception occurred:
      File "conf.py", line 11, in <module>
        import sphinxjp.themes
    ImportError: No module named sphinxjp.themes
    The full traceback has been saved in c:\users\abdelo~1\appdata\local\temp\sphinx
    -err-wzgl0z.log, if you want to report the issue to the developers.
    Please also report this if it was a user error, so that a better error message c
    an be provided next time.
    A bug report can be filed in the tracker at <https://bitbucket.org/birkenfeld/sp
    hinx/issues/>. Thanks!
    

    正如您所看到的,已经安装了扩展程序!所以我必须再次运行它才能运行。

1 个答案:

答案 0 :(得分:1)

安装扩展程序后,它会创建一个.pth文件,通常在导入site.py的初始化期间处理该文件。除其他外,.pth文件指定必须添加到sys.path的其他项目,以便可以导入新的扩展名。

因此,您的脚本需要采取措施在安装后显式处理.pth文件。一种方法是使用属于pkg_resourcessetuptools模块:

try:
    import sphinxjp.themes
except ImportError:
    from pkg_resources import get_distribution
    from setuptools.command import easy_install
    easy_install.main( ["-U","sphinxjp.themes.basicstrap"] )
    get_distribution('sphinxjp.themes.basicstrap').activate()
    import sphinxjp.themes