O Sphinx é uma ferramenta que permite criar documentação para qualquer finalidade, utilizando uma linguagem de marcação (reStructuredText) e alguns scripts Python↳Python56 conteúdosVSCode + Python + Alexa: Desenvolva e teste skills para alexa localmente com pythonDev (Back & Front) · out 2025Dominando decoradores em Python: um guia completo com exemplosDev (Back & Front) · jan 2025Desenvolvimento de software: diferenças entre Python, JavaScript e JavaGestão Dev & TI · nov 2024Ver tudo em Dev (Back & Front) → para gerar saída em formatos como HTML, LaTeX e PDF.
A maioria dos programadores tem uma certa resistência em criar documentação
Na maioria das vezes, a documentação é parte essencial de projetos e o uso de uma linguagem de marcação pode tornar a escrita muito mais confortável, rápida e menos trabalhosa do que usar um editor WYSIWYG. Como a documentação é feita utilizando uma linguagem de marcação, facilita a utilização de controle de versão e dividir as seções entre diversos colaboradores, tornando a tarefa de criação de documentação ainda mais rápida, evitando problemas de acesso e gravação quando se trabalha em um único arquivo.
O Sphinx é muito prático e objetivo, faz com que os programadores tenham interesse e vontade em escrever documentações.
Muitas distribuições GNU/Linux↳Linux34 conteúdosKali Linux em um Servidor VPS: como, quando e por que usar?DevSecOps · dez 2024Construindo um Windows Service ou Linux Daemon com Worker Service & .NET Core – Parte 2Dev (Back & Front) · jul 2020Criando uma WebApi utilizando .NET, Linux e VSCodeDev (Back & Front) · ago 2019Ver tudo em DevSecOps → já possuem o pacote do python-sphinx pronto, bastando um apt-get install python-sphinx (para Debian e Ubuntu) ou yum install python-sphinx (como Fedora/Red Hat/CentOS). Em outras distribuições e sistemas operacionais como Mac ou Windows, é necessário ter o Python instalado, pode-se utilizar o comando easy_install -U Sphinx para instalar o pacote e suas dependências (como Jinja) para ter o Sphinx e suas dependências instaladas.
Uma vez instalado, basta iniciar a criação de seu projeto de documentação com o utilitário sphinx-quickstart, a saída será como no exemplo abaixo:
anderson@yoda:~/tmp$ sphinx-quickstart <br />Welcome to the Sphinx quickstart utility.<br /><br />Please enter values for the following settings (just press Enter to<br />accept a default value, if one is given in brackets).<br /><br />Enter the root path for documentation.<br />> Root path for the documentation [.]: <br /><br />You have two options for placing the build directory for Sphinx output.<br /><br />Either, you use a directory "_build" within the root path, or you separate<br />"source" and "build" directories within the root path.<br />> Separate source and build directories (y/N) [n]: y<br /><br />Inside the root directory, two more directories will be created; "_templates"<br />for custom HTML templates and "_static" for custom stylesheets and other static<br />files. You can enter another prefix (such as ".") to replace the underscore.<br />> Name prefix for templates and static dir [_]: <br /><br />The project name will occur in several places in the built documentation.<br />> Project name: Teste Sphinx <br />> Author name(s): Christiano Anderson<br /><br />Sphinx has the notion of a "version" and a "release" for the<br />software. Each version can have multiple releases. For example, for<br />Python the version is something like 2.5 or 3.0, while the release is<br />something like 2.5.1 or 3.0a1. If you don't need this dual structure,<br />just set both to the same value.<br />> Project version: 1.0<br />> Project release [1.0]: <br /><br />The file name suffix for source files. Commonly, this is either ".txt"<br />or ".rst". Only files with this suffix are considered documents.<br />> Source file suffix [.rst]: <br /><br />One document is special in that it is considered the top node of the<br />"contents tree", that is, it is the root of the hierarchical structure<br />of the documents. Normally, this is "index", but if your "index"<br />document is a custom template, you can also set this to another filename.<br />> Name of your master document (without suffix) [index]: <br /><br />Please indicate if you want to use one of the following Sphinx extensions:<br />> autodoc: automatically insert docstrings from modules (y/N) [n]: <br />> doctest: automatically test code snippets in doctest blocks (y/N) [n]: <br />> intersphinx: link between Sphinx documentation of different projects (y/N) [n]: <br />> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]: <br />> coverage: checks for documentation coverage (y/N) [n]: <br />> pngmath: include math, rendered as PNG images (y/N) [n]: <br />> jsmath: include math, rendered in the browser by JSMath (y/N) [n]: <br />> ifconfig: conditional inclusion of content based on config values (y/N) [n]: <br /><br />A Makefile and a Windows command file can be generated for you so that you<br />only have to run e.g. `make html' instead of invoking sphinx-build<br />directly.<br />> Create Makefile? (Y/n) [y]: <br />> Create Windows command file? (Y/n) [y]: n<br /><br />Finished: An initial directory structure has been created.<br /><br />You should now populate your master file ./source/index.rst and create other documentation<br />source files. Use the Makefile to build the docs, like so:<br /> make builder<br />where "builder" is one of the supported builders, e.g. html, latex or linkcheckDepois de ter respondido as perguntas acima, um diretório com um Makefile e os subdiretórios build e source serão criados. No source, você vai trabalhar na criação do documento, enquanto que no build, ficará sua documentação depois de gerada.
Dentro do build, terá um arquivo conf.py, que agrega todos os parâmetros de configuração. As opções estão comentadas, com um breve resumo de cada parâmetro, mas recomendo alterar a linha “language” para pt_BR se estiver criando sua documentação em português. Ficará desse jeito:
# The language for content autogenerated by Sphinx. Refer to documentation<br /># for a list of supported languages.<br />language = 'pt_BR'Depois de configurado, basta criar seus documentos, são arquivos .rst com a formatação bem semelhante de wiki. Um exemplo de documento (arquivo intro.rst):
Título<br />======<br /><br />A linguagem de marcação é semelhante a muitos wikis.<br /><br />Subtítulo<br />---------<br /><br />Você também pode usar **negrito**, *itálico*.<br /><br />Uma lista enumerada ficaria assim:<br /><br /> #. Primeira linha<br /> #. Segunda linha<br /> #. Terceira linha<br /><br />.. hint::<br /> Aqui você pode colocar uma dica Depois basta referenciar seus arquivos dentro do index.rst, não sendo necessário colocar a extensão .rst. Exemplo:
.. Teste Sphinx documentation master file, created by<br /> sphinx-quickstart on Sun Oct 24 18:19:06 2010.<br /> You can adapt this file completely to your liking, but it should at least<br /> contain the root `toctree` directive.<br /><br />Welcome to Teste Sphinx's documentation!<br />========================================<br /><br />Contents:<br /><br />.. toctree::<br /> :maxdepth: 2<br /><br /> intro<br /><br />Indices and tables<br />==================<br /><br />* :ref:`genindex`<br />* :ref:`modindex`<br />* :ref:`search`Para gerar a saída em PDF, basta digitar make latex no diretório principal da documentação. Depois basta entrar no diretório build/latex e digitar make all-pdf para que o PDF seja gerado, como no exemplo abaixo (a página do nosso exemplo de documento):

Dicas aos usuários de Debian/Ubuntu (e provavelmente outras distribuições): instale o pacote texlive-full para que o suporte a geração de PDF funcione.
Além da tela acima, o pacote gera automaticamente o índice, índice de imagens, índice de tabelas e demais facilidades utilizadas em documentação. A qualidade do documento fica realmente muito profissional, excelente para documentar projetos de software, criar material para treinamentos, apresentações e outras necessidades com toda a agilidade de trabalhar diretamente com linguagem de marcação. Para saber mais, visite os links abaixo:
Veja todas as marcações disponíveis em reStructuredText quickstart.
Visite também o site do projeto: Python Sphinx





