Sphinx로 Python기반 문서 작성하기

Reading time ~7 minutes

이번 글에서는 Sphinx로 Python 기반 문서를 만드는 방법에 대해 알아보겠습니다.

참고 자료 :

https://kshyun87.tistory.com/63

http://www.incodom.kr/Sphinx

1. Sphinx란?

Sphinx란 Python 파일(.py)을 읽어들여, 해당 내용을 바탕으로 문서화를 해주는 Package 입니다. PyTorch의 경우에도 이를 활용하고 있습니다.

2. Sphinx 설치

우선 설치를 위해 아래 명령어를 명령프롬프트(cmd)에 입력해줍니다.

In[1]:

$ pip install Sphinx

참고로, 본글은 Sphinx 1.7.4 버전 기준으로 작성되었습니다.

3. Quickstart를 통한 빠른 문서 생성

설치가 다 되었다면, 이제 문서를 만들고자하는 폴더에 들어갑니다.

보통은 root 폴더 안에는 여러 폴더와 ‘.py’ 문서들이 존재하기 때문에, root 폴더에 바로 문서화 작업을 진행하지 않습니다. 따라서, ‘./docs’과 같이 root 폴더 안에 문서화를 위한 폴더를 하나 더 만들어줍니다. 1.7.4 버전에서는 sphinx-quickstart시 root path를 설정할 수 없기 때문에 이 과정을 거칩니다.

Root 폴더 안에서 설정한 문서화를 위한 폴더(이하 docs)에서 cmd를 키고, 다음 명령어를 입력해줍니다.

In[2]:

$ sphinx-quickstart

그럼 아래와 같이 여러 문구를 묻게됩니다. 각 문구에 맞추어 입력해주시면 됩니다. y로 해야하는 것은 따로 (ENTER)가 아닌 y로 해놓았으니 참조바랍니다.

In[3]:

Welcome to the Sphinx 1.7.4 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: (ENTER)

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]: (ENTER)

The project name will occur in several places in the built documentation.
> Project name: torchattacks
> Author name(s): harrykim
> Project release []: 1.2

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]: (ENTER)

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]: (ENTER)

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]: (ENTER)

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]: (ENTER)
Indicate which of the following Sphinx extensions should be enabled:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: (ENTER)
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: (ENTER)
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: y
> coverage: checks for documentation coverage (y/n) [n]: (ENTER)
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: y
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: (ENTER)
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: (ENTER)

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]: (ENTER)
> Create Windows command file? (y/n) [y]: (ENTER)

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

4. 문서 작성

문서 작성을 위해서는 몇 가지 작업이 필요합니다.

우선, root 폴더가 아닌, docs 폴더에서 문서들을 생성하였으므로 참조 주소를 root 폴더로 변경해주어야합니다.

이를 위해, /docs/conf.py를 수정해봅시다.

conf.py에 들어가면, 아래와 같이 주석처리된 부분이 있을텐데 이를 해제해주시면 됩니다. 그럼 절대경로가 root 폴더로 변경되어 문서 작업을 간편하게 할 수 있습니다.

In[4]:

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

추가적으로 테마의 경우에도 다양한 테마를 사용할 수 있기 때문에, conf.py에서 html_theme에 해당하는 변수를 바꾸어주시면됩니다.

In[5]:

html_theme = 'sphinx_rtd_theme'

물론, 해당 테마는 따로 설치해주셔야합니다.

In[6]:

$ pip install sphinx_rtd_theme

이제 html을 정상적으로 생성할 수 있습니다! docs 폴더에서 아래 명령어를 입력해봅시다.

In[7]:

make html

/docs/_build/html 안에 index.html이 생기게 되고, 해당 파일을 클릭하면 웹페이지를 확인할 수 있습니다!

5. 문서 수정

이제, 문서 안의 내용을 수정하고 싶다면 docs/index.rst를 수정해주셔야 합니다. 해당 파일은 index.html에 보이는 문서 내용을 수정할 수 있으며, 아마 처음에는 아래와 같을 것입니다.

In[8]:

Welcome to torchattacks's documentation!
========================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

toctree란 트리 구조를 지원하는 목차이고, 아래 이제 Indices and tables부터가 내용을 의미합니다. 여기부터는 rst, sphinx 문법을 통해 내용을 수정하면 되며, 자세한 내용은 다음 웹페이지를 참고바랍니다. https://fwani.tistory.com/3

6. Package 내용 반영하기

지금부터는 Sphinx를 Package 설명 문서로 활용하고자 할 때 참조할만한 내용입니다. rst의 구조부터 설명드리자면, index.rst를 기반으로 다른 rst들을 연결하며 사용할 수 있습니다. 문서와 연결된 문서를 만들기 위해서는 아래와 같이 마지막 줄을 추가해주면 됩니다.

In[9]:

Welcome to torchattacks's documentation!
========================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   attack

이것이 의미하는 바는 torchattacks의 목차에 attack이라는 rst를 sub-page로 추가하겠다라는 의미이며, 따라서 attack.rst를 또 만들어주셔야합니다. 마찬가지로 index.rst가 있는 docs 폴더 안에 attack.rst를 만들어줍니다.

In[10]:

Attack
========================================

.. automodule:: torchattacks 
   :members:
   :undoc-members:
   :show-inheritance:

   Modules

   -------

   .. automodule:: torchattacks.attack
    :members:

설명을 차근차근하자면, 우선 attack이라는 sub-page에는 (1) Attack이라는 큰 제목이 달리게 되며, (2) torchattacks에 있는 파일들을 바탕으로 생성이 된다라는 것입니다. (3) 그리고 Modules라는 소제목이 띄워진 후에, (4) 밑에 root/torchattacks 폴더 안의 attack.py 파일을 바탕으로 문서가 생성됩니다. 물론 해당 문서 안의 py는 여러개가 될 수 있으며 그 경우 아래와 같이 써주시면 됩니다.

In[11]:

Attack
========================================

.. automodule:: torchattacks 
   :members:
   :undoc-members:
   :show-inheritance:

   Modules

   -------

   Attack1
   ~~~~~~~~~
   .. automodule:: torchattacks.attack1
    :members:
            
   Attack2
   ~~~~~~~~~
   .. automodule:: torchattacks.attack2
    :members:
            
   Attack3
   ~~~~~~~~~
   .. automodule:: torchattacks.attack3
    :members:

7. Google form 활용하기

기본 Sphinx 설정은 아래와 같은 형식을 요구합니다.

In[12]:

class PGD(Attack):
    r"""
    'Towards Deep Learning Models Resistant to Adversarial Attacks'
    [https://arxiv.org/abs/1706.06083]

    :param float eps: epsilon in the paper. (DEFALUT : 0.3)
    :param float alpha: alpha in the paper. (DEFALUT : 2/255)
    """

하지만, torch 문서에서도 보시면 보통 아래와 같이 되어있는 경우가 많습니다.

In[13]:

class PGD(Attack):
    r"""
    'Towards Deep Learning Models Resistant to Adversarial Attacks'
    [https://arxiv.org/abs/1706.06083]

    Arguments:
        eps (float): epsilon in the paper. (DEFALUT : 0.3)
        alpha (float): alpha in the paper. (DEFALUT : 2/255)
        
    """

제 경우에도 후자가 조금 더 깔끔하기 때문에 후자를 선호하며, 이를 ‘Google Python Style Guide’이라고 부릅니다. 해당 Style을 적용한 sphinx를 사용하고 싶을 때에는 conf.py의 아래 부분을 변경해주시면 됩니다.

In[14]:

extensions = ['sphinx.ext.napoleon',
             ...]

그 후 make html을 통해 보시면 Google Python Style Guide를 통해 문서화 작업을 하는 것을 확인하실 수 있습니다!

8. RTD(readthedocs)를 통한 배포

만약, 만들어진 설명을 공개하고 싶다면 RTD를 활용하는 것이 가장 빠르다고 할 수 있겠습니다.

https://readthedocs.org/는 문서를 무료로 hosting할 수 있도록 도와주는 사이트이며, sphinx를 통해 만든 문서는 매우 github과 연동하면 매우 간단히 배포할 수 있습니다. 물론, 무료이다보니 광고가 붙고 해당 광고는 RTD에게 넘어가게 됩니다.

크게 세 가지 부분으로 나뉘게 됩니다.

  1. RTD 가입
  2. Github Push
  3. RTD와 Github의 연동

Github과 연동을 하면, RTD를 바꿀 필요가 없이 Gitbhub에 Push하면 자동으로 RTD가 업데이트를 해주기 때문에 그런 점이 매우 편리하다고 할 수 있습니다.

8.1. RTD 가입

RTD 가입은 이메일 혹은 Github 계정으로 진행할 수 있으며, 본 편에서는 Github과 연동할 것이기 때문에 github으로 가입하는 것을 추천드립니다.

가입이 완료되었다면 이제 Github을 준비할 차례입니다.

8.2 Github Push

Github에 Push하실 때의 주의사항은 아래와 같습니다.

  1. Package 폴더에 requirements.txt가 있어야한다.
  2. docs 폴더 안에 underbar(_)가 붙은 폴더는 필요없다.
  3. conf.py가 단 한 개 존재해야하며, 이 외의 구조도 왠만하면 바꾸지 않는다.

특히, python package 설명 문서를 작성할 때는 autodoc을 활용하기 때문에 requirements 문서가 없으면 autodoc이 제대로 작동하지 못합니다. 따라서 꼭 이 점 주의하시길 바랍니다. 나머지는 여태까지 활동 중에서 따로 행한 것이 없다면 체크만해주시고 넘어가시면 됩니다.

준비가 되었다면, Github의 해당 package repository로 docs 문서 및 requirements.txt 파일을 push 해주시면 됩니다.

8.3 RTD와 Github의 연동

우선은 가입한 아이디로 RTD에 들어가서, 우측 상단에 있는 자신의 아이디를 클릭하거나 https://readthedocs.org/dashboard/로 접속합니다. 그럼 아래와 같은 화면이 뜨게됩니다. 본 화면의 Projects에는 현재 제가 연동 중인 Repository가 확인되는 것이며, 처음 가입했을 경우 없는 것이 정상입니다.

Dashboard

이제 여기서 “Import a Project”를 눌러줍니다. 그럼 아래와 같이 Github에서 어떤 Repository를 연동할 건지 뜨게 됩니다. 아래 그림에서 보이는 것처럼 이미 연동 중인 Repository는 화살표로 연결 표시가 뜨며, 연동 가능한 것은 (+) 표시가 뜹니다. 연동하고자 하는 Repository를 선택합니다.

Dashboard

그럼 해당 Repository에 대한 정보를 보여주고, 맞는지 확인하라고 합니다. 여기서 맨 마지막 ‘Edit advanced project options’를 체크하고 넘어갑시다.

Dashboard

그럼 아래와 같이 Extra Detail을 설정할 수 있고, 이 때 ‘Documentation type’이 Sphinx Html인 것을 다시 한 번 확인합니다. 이 외의 것은 각자 취향에 따라 입력해주시면 됩니다.

Dashboard

이제 버튼을 클릭하면 아래와 같이 Project가 생성됩니다! 이제 Build a version을 클릭하여, 문서를 만들 수 있습니다.

Dashboard

Build version을 클릭하면 아래와 같이 Github에 Push한 docs 폴더를 바탕으로 문서가 Build 됩니다.

Dashboard

이제 마지막으로 Github에서의 변화가 일어났을 때 웹페이지도 수정할 수 있도록 연동을 해주면 되는데, 이는 “Admin” 옵션의 “Integrations”에서 설정할 수 있습니다.

Dashboard

Dashboard

Integreations에서 “GitHub incoming webhook”을 추가해주시면, 따로 RTD를 건드리지 않아도 자동적으로 반영이 됩니다.

Build가 완료되면, 아래처럼 "”Build Completed” 표시가 뜨고, View docs를 통해 문서를 확인하고, View raw를 통해 build 중 오류가 있었는지 확인 가능합니다. 특히 View raw를 통해 어떤 부분에서 Error가 났는지 꼭 체크해주셔야합니다.

Dashboard

주피터 노트북 찾기

Published on June 07, 2021

파이썬 Super 명령 알아보기

Published on July 06, 2021