Sphinx 설치
파이썬 코드 독스를 작성하기 위해 Sphinx를 사용하기로 했다.
출력 포맷이 문서뿐만 아니라 html도 호환이 가능하다는 장점이 있다.
먼저 사용을 위해서는 sphinx 라이브러리를 설치해 주어야 한다.
# pip install sphinx
Docstring 작성을 위한 Sphinx 셋팅
Sphinx 라이브러리 설치가 완료되었다면 기본 셋팅이 필요하다.
- quickstart 명령어를 통해 Docs 디렉토리를 생성한다.
- *.rst 파일을 변환하여 Docs 파일을 생성한다.
- make html 명령어를 통해 python 코드 컴파일 후 html 파일을 생성한다.
디렉토리 생성
# cd docs
# sphinx-quickstart
...
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]: y
The project name will occur in several places in the built documentation.
> Project name: project name
> Author name(s): your name
> Project release []: version
...
For a list of supported codes, see
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> Project language [en]: ko
- 디렉토리 구조
project │ ├─┬─ docs │ ├─ build │ ├─┬─ source │ │ └─ conf.py │ ├─ make.bat │ └─ Makefile │ ├─┬─ lib │ └─ calculator.py └─ main.py
폴더별로 정리되어 있는 것을 선호해서 프로젝트 경로 내에 docs 라는 폴더를 생성한 후 진행했다.
Separate source and build directories (y/n) [n]: y
- build와 source 파일을 분류할 것인지 통합할 것인지 지정할 수 있다.
- y 옵션을 선택하게 되면 위와 같이 build, source 폴더가 나뉘어 생성된다.
*.rst 파일 생성 및 셋팅
# conf.py
# 해당 부분의 주석 해제 후 경로를 지정해 준다.
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
...
# extensions 에 아래와 같이 추가해 준다.
# sphinx.ext.autodoc : 문서화 할 모듈을 import하기 위해 사용
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
'sphinx.ext.intersphinx', 'sphinx.ext.todo',
'sphinx.ext.ifconfig', 'sphinx.ext.viewcode',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.autosummary']
sys.path.insert(0, os.path.abspath('../../'))
: 해당 경로를 기준으로 docs를 작성하고자 하는 파일을 컴파일하기 때문에 유의해야 함.- 파이썬 코드 내에 상대경로가 있다면 절대경로로 바꾸어 주어야 한다. 컴파일 시 경로에 대한 모든 기준은
conf.py
에서 지정한 절대경로이기 때문.
# cd ..
# sphinx-apidoc.exe -f -o docs/source .
이제 docs/source
경로에 *.rst 파일이 생성된 것을 확인할 수 있다.
# docs/source/index.rst
Welcome to (your project) documentation!
==========================================
.. toctree::
:maxdepth: 2
:caption: Contents:
modules
maxdepth
: 컨텐츠에서 보여줄 목차 단계- 해당 컨텐츠에서 보여줄 *.rst 파일명
docs 빌드
make 명령어를 통해 생성된 코드와 *.rst 파일을 docs 로 변환한다.
# docs\make.bat html
docs/build/html/index.html
파일이 생성된 것을 확인할 수 있음.
docstring 포맷 설정
sphinx 는 기본적으로 reST(reStructuredText) 스타일만 지원한다.
- 파이썬 docstring 스타일은 이 링크 를 참고
NumPy 또는 Google 스타일을 사용을 위해서는 추가적인 설치와 설정이 필요하다.
# pip install sphinxcontrib-napoleon
# conf.py
# 아래와 같이 추가
extensions = ['sphinxcontrib.napoleon']
sphinx 사용 예시
https://github.com/5xJIN/sphinx_example
테마 설정
html 빌드 시 해당 페이지에 대한 테마를 지정할 수 있다.
이 링크에 접속하면 여러가지 sphinx 테마 목록이 있는데 취향에 맞게 테마 install 후 지정하여 사용하면 된다.
내가 예시로 사용한 테마는 Material
로 이 테마를 기준으로 설정 방법을 설명할 예정이다. 또는 각 테마의 데모 페이지에 접속하면 적용 방법이 있으므로 보고 따라하는 것을 추천한다.
테마 라이브러리 설치
pip install sphinx-material
테마 설정
#conf.py
html_theme = 'sphinx_material'
설정 파일 내에 테마 설정까지 마친 후 재빌드를 하면 테마가 적용된 것을 확인할 수 있다.
# docs\make.bat html
메인 화면
docstring 적용 화면