如何使 BuildDoc 仅在从 setup.py 文件安装 python-sphinx 时才工作?

how to make BuildDoc work only when python-sphinx is installed from setup.py file?

我的项目有一个 setup.py 文件 FlashText :

from setuptools import setup, Command
from sphinx.setup_command import BuildDoc

setup(
    .
    .
    cmdclass={'test': PyTest, 'build_sphinx': BuildDoc},
)
如果 python-sphinx 没有安装,

pip install flashtext 失败。

ImportError: No module named sphinx.setup_command


Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-LI0I_O/flashtext/

这将解决该问题:

sudo apt-get install python-sphinx

我需要的是,如果有人没有安装 python-sphinx,那么他们也应该能够安装该库。我该如何处理?

例如py.test是这样处理的:

import subprocess


class PyTest(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call(['py.test'])
        raise SystemExit(errno)

PS:完整代码可在 github https://github.com/vi3k6i5/flashtext

cmdclass={'test': PyTest}

try:
    from sphinx.setup_command import BuildDoc
    cmdclass['build_sphinx'] = BuildDoc
except ImportError:
    print('WARNING: sphinx not available, not building docs')

setup(
    .
    .
    cmdclass=cmdclass
)