Github Page

레이블이 Lang-Python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Lang-Python인 게시물을 표시합니다. 모든 게시물 표시

1/02/2026

Github Pages/Mkdocs/ReadMe 정리2

1. Mkdocs 와 Github 문서정리 

아무리 생각을 해보도 Github Pages로는 Mkdocs가 가장 적절한 것으로 판단이 되어진다.
여러 개를 써봤지만, 이렇게 깔끔하게 내 취향을 좋게 맞춰주는게 많지 않을 듯하다.

Why
Markdown 문서 기반으로 Web hosting이 쉽게 해주기 때문이다.

Limitations
다만 기술 문서 관점에서 다시 평가하면,
reStructuredText(.rst) 중심의 Sphinx가 더 적합한 선택으로 보인다 (Sphinx도 Markdown 지원함)
Doxygen + Breathe + Exhale 의 조합이 가장 낫을 듯하다. 
여기에 Call Flow도 넣으면 더 좋고 (이외에 PDF, ePUB 등) 

  • Github 와 Mkdocs
현재 Github의 Markdown과 Mkdocs가 가장 적절하게 운영할 수 있는 것 같으며, 최근 변화에도 그런 것 같다.   

  • ReadTheDoc 사용 (Sphinx 와 mkdocs)
현재도 ReadTheDoc를 무료로 사용하고 있으며, 이 사이트는 Sphinx 와 Mkdocs 둘 다 지원

  • Readme 와 ReadtheDocs 가격비교 
ReadTheDoc 괜찮지만, 아래의 Readme도 한번 사용해봐야 겠다. 무료로 써 본 다음에 결정 

Readme 가격 
무료로 쓰려고 했으나, 실패

ReadtheDocs 가격 
현재도 사용중이며, 다만 서버가 간혹 문제가 발생하는 경우가 발생하지만 무료로 이것만으로도 만족^^



1.1  Mkdocs 의 설치 

mkdocs는 구글로 검색을 하면 쉽게 다 알 수 있으며, 작성 방법도 너무 쉬우므로, 
아래와 같이 각 Link만 연결하도록 한다. 

Mkdocs 관련설명


  • Mkdocs 의 Plugin (Mkdocs 문서 to PDF)

  • Mkdoc 의 기본 Manual 
mkdocs의 기본 Manaul 이므로 당연히 필독!

  • Mkdocs Material Manual
Material 세련되게 사용하고 싶다면, 아래의 사이트는 전체 다 세부적으로 읽어보는 것을 추천 
다만, 일반 Markdown 방식과 호환 안되는 경우가 있으므로 Material Theme 용으로만 사용. 
Material Convention (Symbol) 알아두고, 각 아이콘을 기억 
Github Action 기반의 Github Pages 설정 (개선을 하시면 더 좋고)
세부설정-Material Setup 부분 반드시 확인 
(색상/Fonts/Lanuage/logo, Google Analytics 등 )
세부설정-Icon 과 좀 더 세련된 박스 제공 
세부설정-markdown table도 더 세련되게 
세부설정-icon/emoji도 좀 더 세련되게 
세부설정-Material Plugins 기능들 (다양함, Blogs처럼 사용가능)

  • Python 기본설치 
Python 기반으로 기본설치 
$ pip install mkdocs                           // Python mkdocs 설치 
$ pip install pymdown-extensions               // markdown extension 


Mkdocs 설정관련내용 (Python 설치 및 설정)
쉽게 설명을 해주고, 자주 업데이트 해주셔서 감사하다. 

  • mkdocs theme 설치 
$ pip install mkdocs-material                  // mkdocs theme
$ pip install mkdocs-material-extensions       // mkdocs theme
$ pip install mkdocs-rtd-dropdown              // mkdocs theme 

  • Mkdocs 의 Themes
상위 이외에 다양한 Themes 이 존재하므로 설치해서 사용 
현재 material만 꾸준히 Update되고 있으며, 이것을 사용하는게 맞을 것 같지만, 이상하게 더 readthedocs가 더 끌린다. 

  • 기타 Plug 설치 
$ pip install mkdocs-mermaid2-plugin           // mermaid2 
$ pip install mkdocs-with-pdf                  // mkdoc to pdf

PDF의 경우, 현재 한글이 완벽히 지원되지 않음 주의! 
PDF의 경우, 현재 Browser에서 직접 인쇄를 이용하여 인쇄하는게 가장 낫을 듯 싶다. 

1.2  mkdocs File 구성 

Github 쉽게 공유되어지며, 아래와 같이 구성한다. 

$ tree
docs
└── index.md    


1.3  mkdocs 관련설정 

참고만 하고, 실제는 좀 더 세련되게~~ 사용해야지 (Google Analytics도 사용하고)

mkdocs.yml (theme: marterial)




mkdocs 의 material mkdocs.yml 예제 

mkdocs 의 material의 세부변경사항 이해 


mkdocs 의 theme 
readthedocs 와 rtd-dropdown 
  
mkdocs 의 theme 종류 

  • mkdocs 의 Chart/Images, Tables, and Graph 
MkDocs GLightbox 
plantuml-markdown
mermaid2 
charts 
Markdown blockdiag 
drawio-exporter 

mkdocs 의 pdf 와 epub

docgen 


2. GitHub Pages 자동연동 

Github Action 으로 쉽게 Github Pages에 연동이 가능하므로, 다양하게 사용이 가능하다.
Google Analytics 본인 직접 설정도 가능하다.
언어도 2개 이상도 다 지원가능하며, 다양하게 사용가능하다.
다만 언어를 2개 사용하면, 골치 아픈게 2개의 언어로 다 따로 작성을 해야해서~ 

  • 나만의 Profile 완성 
세부내용은 상위와 많이 다르나, Marterial Manual을 보면서 수정을 하면, 쉽게 할 수 있다고 생각한다.

8/11/2023

Mkdoc 와 Github 문서정리

1. Mkdocs 

이전에 Sphinx 와 Mkdocs 기반으로 환경을 구축하여 간단하게 테스트를 한적이 있는데, 
Mkdocs만으로 쉽게 Github의 Markdown 문서를 관리하는 법을 간단히 소개한다. 

이유는 Mkdocs는 Markdown 으로만 사용하기 때문에 Github와 더 잘 어울린다. 
다만 아쉬운것은 Sphinx에 비해 Plugin이 좀 떨어질 뿐이다. 

  • ReadTheDoc (Mkdocs/Sphinx 둘 다 지원)
ReadTheDoc 사용법 및 Sphinx 와 Mkdocs 비교 (Doxygen 기본 사용법)

  • Mermaid.JS 사용예제
Github에서는 이미 Markdown에 mermaid를 제공하지만, 아래와 같이 Mermaid.js로 해도됨


  • 기본설치 및 테스트 진행
가급적 Linux 기반으로 설치하도록 하며, Window에서는 WSL를 통해서 하자  
$ pip install mkdocs
$ sudo apt install mkdocs 
$ mkdocs new mkdocs-project
$ cd mkdocs-project
$ ls docs mkdocs.yml $ cat mkdocs.yml #설정확인 site_name: My Docs $ mkdocs serve # 에러발생하여 아래 Package Version 변경으로 해결 INFO - Building documentation... INFO - Cleaning site directory INFO - Documentation built in 0.08 seconds INFO - [16:11:08] Watching paths for changes: 'docs', 'mkdocs.yml' INFO - [16:11:08] Serving on http://127.0.0.1:8000/ INFO - [16:11:11] Browser connected: http://127.0.0.1:8000/ INFO - Shutting down... $ mkdocs build # site에 webpapage 와 xml 생성확인 $ mkdocs build INFO - Cleaning site directory INFO - Building documentation to directory: /home/jhlee/project/mkdocs-project/site INFO - Documentation built in 0.03 seconds



1.1 Mkdocs PDF 배포 

아래와 같이  mkdocs-with-pdf를 별도 설치진행 
$ pip install mkdocs-with-pdf 

$ vi mkdocs.yml  #plugins 추가 pdf 
site_name: My Docs
plugins:
    - with-pdf

$ mkdocs build  # PDF 파일 과 HTML 파일 생성  
INFO     -  Cleaning site directory
INFO     -  Building documentation to directory: /home/jhlee/project/mkdocs-project/site
INFO     -  Number headings up to level 3.
INFO     -  Generate a table of contents up to heading level 2.
INFO     -  Generate a cover page with "default_cover.html.j2".
INFO     -  Converting  alignment(workaround).
INFO     -  Rendering for PDF.
INFO     -  Output a PDF to "/home/jhlee/project/mkdocs-project/site/pdf/document.pdf".
INFO     -  Converting 1 articles to PDF took 0.7s
INFO     -  Documentation built in 0.70 seconds

$ tree      # tree 명령어로 전체구성 다시 확인 
.
├── docs                # docs 밑에, Markdown 구성하여 문서 구성 , 이는 Github에서 호환사용가능
│   └── index.md          # 기본 문서확인
├── mkdocs.yml             # 상위 설정확인
└── site                # mkdocs build 결과 (HTML, PDF)             
    ├── 404.html
    ├── css
    │   ├── base.css
    │   ├── bootstrap.min.css
    │   └── font-awesome.min.css
    ├── fonts
    │   ├── fontawesome-webfont.eot
    │   ├── fontawesome-webfont.svg
    │   ├── fontawesome-webfont.ttf
    │   ├── fontawesome-webfont.woff
    │   └── fontawesome-webfont.woff2
    ├── img
    │   ├── favicon.ico
    │   └── grid.png
    ├── index.html
    ├── js
    │   ├── base.js
    │   ├── bootstrap.min.js
    │   └── jquery-1.10.2.min.js
    ├── pdf
    │   └── document.pdf
    ├── sitemap.xml
    └── sitemap.xml.gz


mkdocs-with-pdf


1.2 CHM (Window HTML 설명서)

chm파일은 Window에 주로 API 설명서를 구성하기 위해서 예전에 많이 사용했다. 

  • chm 파일 viewer 설치  (WSL 설치가능, Linux 지원)
sudo apt-get install xchm 

상위를 실행시키면 쉽게 Viewer 확인 


  • HTML -> CHM 파일 생성 방법 링크 
다 확인해보지 않고 링크만


1.3 mkdocs 문제사항 정리 

Linux에서는 거의 발견못했는데, 주로 Window 기반의 WSL에서 실행했을 경우 발생하였다.  
원인을 보면, 버전의 호환성문제로 각 버전을 맞춰 재설치를 진행

  • mkdocs serve 에러문제 
 AttributeError: 'zipimport.zipimporter' object has no attribute 'exec_module'
$ pip install markdown==3.2.2  # 

 AttributeError: 'EntryPoints' object has no attribute 'get
$ pip install importlib-metadata==4.13.0   # (5.0.0->4.13.0)

  • mkdocs build (plugin)에러문제 
Window에서 실행할 경우 발생 
 OSError: cannot load library 'gobject-2.0-0': error 0x7e.  Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' 

보통 Doxygen을 사용하면, chm file을 많이 사용하는데, Linux에서도 아래와 같이 볼수는 있다.


2. mkdocs 쉬운구성환경 

  • Mkdocs 사용방법정보 
모든정보가 다 이곳에 있어, 간단히 여기서 정리끝날꺼 같다.   


Github 와 연동 예제 


현재 나의 경우, Sphinx 보다는 mkdocs가 좀 더 Github와 Markdown으로 잘되어 이게 더 편한 것 같다. 
설정이야, 본인 theme 부터 변경해서 차근차근사용하면 될꺼 같다. 

1/28/2022

Window Python 설치 및 설정 과 PowerShell

1. Window Python 사용 

Window에서 PS(PowerShell) or CMD에서 python치면 매번 , Microsoft Store의 Python 자동으로 실행이되어 제대로 동작이 안되는데, 
이부분을 설정을 아래와 같이 변경해주자.   

솔직히 Window에서는 Python을 잘 사용하고 싶지 않지만, 어쩔 수 없이 사용해야 하므로 아래와 같이 변경을 해주도록하자. 

  • 시작 -> 앱 실행 별칭 관리 (자동설치 메세지 끄기)
앱 실행별칭관리로 검색하면 쉽게 찾음 
앱 설치 관리자(python)-> 끔 변경 


우선 CMD 나 Power Shell 에서 python 을 치면, 설치하라고 자동 Message가 나오는데, 
앱 실행 별칭관리에서 이를 끄자 

만약, Window 용 Python으로 venv 형식으로 관리하고 싶다면, 아래 Mircrosoft 창에서 설치진행 

Window에서 Python입력하면 Microsoft Store 창 열리는이유 


1.1  Window Python 설치방법 및 종류  

상위 Microsoft Store를 통해서 설치를 해도 되며, 아래의 사이트에서 직접 다운받아 설치를 진행해도 상관 없다. 

  • Python Site Download (현재 두가지로 제공)
  1. Embeddable Package :  Window의 기본 PATH에 설정되지 않아 기본적으로 찾지 못함
  2. Installer Package : Window PATH가 설정되어 기본 Python 동작 
상위에서 다시 32bit or 64bit version 나뉘어짐 (기본 64bit)

  • Window Python 전체 설치방법  
상위 사이트의 2개 와 이외에도 Window 10/11의 Microsoft Store도 설치가능하며, Window 경우는 Python 설치가 좀 복잡하다. 
  1. Embeddable Package : Portable로 아무 위치에 설치하여 실행가능하지만, PATH는 본인이 설정해야하며 venv 처럼 독자적으로 운영가능   
  2. Installer Package:  Window 의 설치버전으로 Program File 에서 설치되어지며, 독자적으로 각각 사용하고자 하면, venv 이용 
  3. Microsoft Store Package:  Window 에서 제공하는 Microsoft Store 설치버전이며, 상위 Installer Package 와 PATH(주의)가 다르며 MS가 가장권장 
  4. 이외 기타 방법: nuget.exe 설치방법, cywin기반 설치, WSL ubuntu 설치 등 생략! 

Window에서 Python 사용하기 

Microsoft Store에서 제공하는 Python도 존재확인  

Nuget 설치방법 


1.2 Embeddable Package for Window

Python Embeddable Package는 PATH 설정되어 있지 않아, 항상 Python을 찾지 못하므로  PATH를 설정하거나, 직접 python.exe를 찾아야 한다. 


  • Embeddable Package 압축해제 후 설정
처음 설치할 경우, Installer Package는 pip가 다 있으므로 괜찮지만, Embeddeable Package는 내부에 존재하지 않아 get-pip.py 를 이용하여 아래와 같이 pip를 설치진행 
  1. get-pip  pip 설치 
  2. PATH 설정 
  3. 설정완료 및 사용방법 

설치방법 Manual

A. Embeddable Package (pip 설치방법)
  1. download  get-pip.py
  2. PATH 설정 (옵션)
PS C:\User\jhlee >  cd D:\Tools\python\python-3.9.13-embed-amd64

PS D:\Tools\python\python-3.9.13-embed-amd64> ./python ./get-pip.py  //인터넷으로 download 후 저장한 후 (https://bootstrap.pypa.io/get-pip.py)
문제가 발생할 경우, 아래와 같이 임시적으로 PATH추가 (pip 못찾음)
//아래 둘중 하나 PATH 설정 앞으로 넣던가 or 뒤로 넣던가, 처음 한번만 아래에서 파일추가하고, 아래에서 파일에 추가
PS D:\Tools\python\python-3.9.13-embed-amd64> $Env:Path += ";D:\Tools\python\python-3.9.13-embed-amd64\Scripts"
or
PS D:\Tools\python\python-3.9.13-embed-amd64> $Env:Path = "D:\Tools\python\python-3.9.13-embed-amd64\Scripts;$Env:Path"

상위 설정한 후에 pip 설치되어진 것을 Scripts에서 확인가능하며, python.exe가 pip 찾도록 PATH를 수정해준다.  


B. python39._pth 파일에 PATH 추가 (Scripts/Lib/Lib\site-packages)

D:\Tools\python\python-3.9.13-embed-amd64\python39._pth 파일 수정

Embededable Python이 실행 될 경우,
아래와 같이 PATH추가하면, pip 설치된 package를 이곳에서 찾으며 아래와 같이 절대 PATH
python39.zip
.
D:\Tools\python\python-3.9.13-embed-amd64\Scripts
D:\Tools\python\python-3.9.13-embed-amd64\Lib
D:\Tools\python\python-3.9.13-embed-amd64\Lib\site-packages

# Uncomment to run site.main() automatically
#import site


  1. Lib/site-packages : Python Module들이 설치되어지는 장소
    1. pip 기반으로 설치하면 이 곳에 설치되어짐 
    2. pip list 와 이름을 비교하여 찾으면 됨 
  2. Scripts: 보통 Python Module or Package를 설치 할 경우, 실행되는 파일 
    1. venv 의 activate도 이곳에 존재 
    2. pip 이곳에 존재 
    3. 이외 package 추가할 때마다 실행파일도 추가되어짐 

참고자료 및 Data 



C. Embeddable Package 사용방법 

상위와 같이 설정 후 pip 기반으로 이외의 Python package 설치진행
사용방법은 PATH에 설정이 안되어있기에, PATH를 설정하고 사용하거나, 직접 절대 PATH로 이용하자.  

  • 사용방법-A  PATH 설정 후 사용 (python.exe 찾기위해서)
Embeddable Package를 설치를 하면 항상 PATH 설정을 해야 하므로, bat or ps1으로 만들어두도록하자. 
귀찮다면 아예 Window에서 시스템설정에서 변경을 해도 될 것 같은데, 이 부분은 나는 하고싶지가 않다. 
PS D:\Tools> $Env:Path += ";D:\Tools\python\python-3.9.13-embed-amd64  //아래와 같이 python 찾기 위해 PATH추가 
PS D:\Tools> $Env:Path += ";D:\Tools\python\python-3.9.13-embed-amd64\Scripts  //아래와 같이 pip 찾기 위해 PATH추가 
or 
PS D:\Tools> $Env:Path = "D:\Tools\python\python-3.9.13-embed-amd64;$Env:Path"
PS D:\Tools> $Env:Path = "D:\Tools\python\python-3.9.13-embed-amd64\Scripts;$Env:Path"
상위 두개의 차이는 PATH의 위치 맨 뒤 or 맨 앞으로 간다. 

  • 사용방법-B python.exe 직접사용 
상위 PATH 설정 필요 없이 python.exe를 찾을 경우, pip의 는 아래와 같이 사용. 

PS D:\Tools> D:\Tools\python\python-3.9.13-embed-amd64\python.exe -m pip list
PS D:\Tools> D:\Tools\python\python-3.9.13-embed-amd64\python.exe -m pip install package 


단점이있는데, Window용이라서 제한적이라서 tk or tkinter의 경우는 Embeddable Package으로는 안되는 것 같다. 
GUI를 사용할거면, Installer Package or Microsoft Sotre Package 을 사용하시길 

Embeddeable 할 경우, Window Python의 tk/tkinter 문제 


1.3 Installer Package for Window

Python Installer Package는 PATH 설정 자동설정되므로, Powershell을 실행할 경우, pip 와 python을 자동으로 찾는다. 
그러므로, 가급적 virtualenv 즉, venv 기반으로 독자적으로 구축해서 사용하자  

  • 설치방법
  1. Add Python xx to PATH 선택 (PATH 추가)
  2. Optional Features 
  3. pip/Document/ 기타 GUI? 

  • 설치사항 확인  
설치전에 기존에 설치되어있는지 확인하자 
설정->앱->설치된 앱 

  • 삭제방법  
설정->앱->설치된 앱  (제거)


가능하다면 python -m venv py310_venv  이런식으로 virtualenv기반으로 사용하자 

다만 주의 해야 할 것이 Python을 여러개 설치할 경우, PATH에 다 Python이 들어가므로, 좀 복잡해지며, 
PATH를 나중에 직접 Control 할 경우도발생한다. 

  • Installer Version PATH 
일반적으로 상위 Installer로 설치했을 경우, PATH이며 이를 알아두도록하자.
C:\Users\jhlee\AppData\Local\Programs\Python\Python38\python.exe


1.4 Microsoft Store Package for Window 

Microsoft가 가장권하는 방식이며, 지금 좀 별로일지 몰라도, 나중에 점차 Power Shell 처럼 괜찮을 것 같음( Power Shell 지금도 수시로 변경됨) 
Microsoft Store 안에도 Python을 제공하며, 자동으로  PATH 설정이 되어진다.  
주의해야 할 것은 , 상위 Installer Package 중 둘 중 하나만 설치하자. 
더불어, 역시 가급적 virtualenv 즉, venv 기반으로 독자적으로 구축해서 사용하자  

Microsoft Windows Python 개발환경설정 

  • 설치방법(Microsoft에서 권장)
기본적으로 Microsoft가 권하는 방식이므로, Powershell에서 python 치면, 나온다.
기타 설정방법 

  • 시작-> 앱실행 별칭관리 (상위참조)
python.exe 끔 변경했다면, Power Shell에서 python.exe는 볼수가 없으므로, 이를 원상복귀하자.  
이 설치와 설정과 같이 움직이므로 이 부분 다시확인  

  • 설치사항 확인 
검색 -> Microsoft Sotre -> python 검색 
현재설치되어짐 반드시 확인 
or 
설정->앱->설치된 앱 

  • PowerShell 설치확인 및 위치확인 (상위 Install Package도 동일)
설치 후 아래 gcm command로 이용하여 설치된 위치 파악 
PS C:\User\jhlee> gcm python // Linux 의 which command와 거의 동일 
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     python.exe                                         0.0.0.0    C:\Users\jhlee\AppData\Local\Microsoft\WindowsApps\python.exe
PS C:\User\jhlee> gcm pip

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     pip.exe                                            0.0.0.0    C:\Users\jhlee\AppData\Local\Microsoft\WindowsApps\pip.exe 

  • PowerShell 에서 venv이용 
virtualenv기반으로 사용하도록 하며, 이 기반으로 설정진행하여 사용하자 
PS C:\User\jhlee\test> pip install virtualenv   // virtualevn 설치하여 venv 사용   

PS C:\User\jhlee\test> python -m venv ../tool_py310_env     // venv 설정 진행 (이름은 목적에 맞게기억하기쉽도록)  

PS C:\User\jhlee\test> ..\tool_py310_env\Scripts\Activate.ps1     // venv 활성화   

(tool_py310_env) PS C:\User\jhlee\test>  pip list     // venv기반으로 이용 및 pip 설치확인 (tkinter 기본제공)   

(tool_py310_env) PS C:\User\jhlee\test>  pip install -r requirement     // venv기반으로 pip 설치    

기본으로 Python Module을 lib/site-packages 에서 찾기 때문에 이 곳에 없으면 확장을 해주자. 

venv 사용법 

  • 삭제방법  
설정->앱->설치된 앱  (제거)


  • Microsoft Store Version PATH 
Python in Microsoft Store (상위 Installer Package PATH가 다름)
C:\Users\jhlee\AppData\Local\Microsoft\WindowsApps\python3.10.exe


1.5 Window 의 PATH 우선순위 변경  

Python 종류가 여러개 설치되어 있다면, PATH 설정변경하여, 실행되는 Python 우선순위를 변경하자 
너무 복잡하면, 가급적 지우는게 마음이 편하다. 
나의 경우, 가급적 PATH에 추가하는 것 보다, 별도의 PATH 설정 Script를 만들어서 이를 확장해서 사용하는 것이 편하다. 

  • Window PATH 길이제한


  • PYTHONPATH
실행중인 동안 sys.path 변수를 사용하여, 이 디렉토리에서 검색되어 모듈을 가져온다고 한다.
각 설치방식마다 조금씩 다르므로 주의 
PS C:\User\jhlee\test> python   // Python 실행 점검   
....
>>>  import sys
>>>  print (sys.path)
 // Python 실행해서 PATH확인, 보통 lib/site-packages 에 기본연결   
>>> import tkinter
>>>  tkinter._test()
 // Python tkinter 동작확인   

  • Window의 PowerShell의 Path 설정법  
Powershell에서 cd 혹은 tree 비롯하여 Linux에서 사용하는 command들이 되므로 각각 다 테스트를 해보도록 하자. 

PS C:\User\jhlee> gcm python   // Linux 의 which command와 거의 동일한 것 같다. 
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     python.exe                                         3.8.101... C:\Users\jhlee\AppData\Local\Programs\...


PS C:\Users\jhlee> $Env:userprofile   //Window Userprofile 환경변수 (CMD으 경우 %userprofile%)
C:\Users\jhlee

PS C:\Users\jhlee> $env:Path  // 현재 본인의 PATH를 확인 (CMD의 경우 %PATH% 이용 )
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files\PuTTY\;C:\Users\jhlee\AppData\Local\Programs\Python\Python38\Scripts\;C:\Users\jhlee\AppData\Local\Programs\Python\Python38\;C:\Users\jhlee\AppData\Local\Microsoft\WindowsApps;;C:\Users\jhlee\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Bandizip\;C:\Program Files\LLVM\bin

아래와 같이 Embeddable 도 같이 추가 
PS C:\Users\jhlee> $Env:Path += ";D:\Tools\python\python-3.9.13-embed-amd64"  // PATH의 뒤에다 추가 (python 중복될 경우, 뒤에 추가했으므로, 우선순위가 낮다)

PS C:\Users\jhlee> $Env:Path = "D:\Tools\python\python-3.9.13-embed-amd64;$Env:Path" // PATH의 앞에다 추가 (python 중복될 경우, 뒤에 추가했으므로, 우선순위가 높다)

PS C:\Users\jhlee> $newtemp += "D:\Tools;"   // Linux 처럼 Shell 변수사용 
PS C:\Users\jhlee> echo $newtemp
F:\Tools;
PS C:\Users\jhlee> Set-Item -Path Env:Path -Value ( $newtemp + $Env:Path ) // PATH의 앞에다 추가 


  • Installer Version 과 Microsoft Sotre Version  PATH가 꼬이는 경우 
상위설명 했듯이 두개의 Version은 PATH가 다르며, 가급적 한개를 선택해서 사용하자 
나의 경우, 기존에 설치된 Python을 지워서 해결했으나, 두개를 다 사용해야 하는 경우 발생한다면, PATH로 조절을 하자. 



2. ESP32의 CMD 와 PowerShell 설정 

ESP32의 경우 기본이 Python venv 기반으로 설치되어 있어, 이를 활성화 하려면, activate를 해줘야한다.  
ESP-IDF를 설치했다면, 이 관련된 위치에서 아래와 같이 export를 이용하여 ESP-IDF 설정가능하다. 

  • ESP-IDF 설정
  1. venv activate 
  2. export 개발환경 

  • ESP-IDF CMD로 실행할 경우
  1. ESP32 Python 의 venv를 activate    (ESP-IDF 관련 Python venv로 설치되어짐)
  2. ESP-IDF export 진행 
%userprofile%\.espressif\python_env\idf4.2_py3.8_env\Scripts\activate.bat  
%userprofile%\esp\esp-idf\export.bat 

  • ESP-IDF Powershell 실행할 경우   
동일하지만, 상위보다 기능이 부족하게 지원이 되므로, 가급적 CMD로 사용추천 
$Env:userprofile\.espressif\python_env\idf4.2_py3.8_env\Scripts\activate.ps1
$Env:userprofile\esp\esp-idf\export.ps1

  • ESP-IDF PowerShell 실행확인 
C:\Users\jhlee\.espressif\python_env\idf4.2_py3.8_env\Scripts\activate.ps1  //venv enable
or 
$Env:userprofile\.espressif\python_env\idf4.2_py3.8_env\Scripts\activate.ps1 //venv enable 이지만 tab을 한번 눌러주면 상위로 변경
(idf4.2_py3.8_env) PS C:\Users\jhlee>
(idf4.2_py3.8_env) PS C:\Users\jhlee> C:\Users\jhlee\esp\esp-idf\export.ps1   //ESP-IDF 환경 
or 
(idf4.2_py3.8_env) PS C:\Users\jhlee> $Env:userprofile\esp\esp-idf\export.ps1  //ESP-IDF 환경, tab을 한번 눌러주면 상위로 변경 

esp에서는 idf.py/esptool.py 이외 다양한 기능을 제공하는데, CMD/PowerShell에서 차이가 좀 있다. 


2.1  ESP32 PowerShell 설정 변경방법  

본인이 직접 PowerShell 환경을 좀 더 개선하고 싶다면, 아래와 같이 해보도록하자. 

  • ESP32 의 관련설정 문제사항 
venv activate만 진행하면 path는 아래가 맨 앞으로만 추가되며 python만 지원되며 
ESP32의 전체개발환경에서 필요한 것을 모두 지원해주지 못한다.

   C:\Users\jhlee\.espressif\python_env\idf4.2_py3.8_env/Scripts;


  • ESP32의 PowerShell export.ps1 확인  
esp32 개발환경에서 별도로 export 전용 shell이 제공하며 이를 이용하면 쉽게 환경설정가능 
PS C:\xxx >  cat C:\Users\jhlee\esp\esp-idf\export.ps1
Added to PATH
-------------
C:\Users\jhlee\esp\esp-idf\components\esptool_py\esptool
C:\Users\jhlee\esp\esp-idf\components\app_update
C:\Users\jhlee\esp\esp-idf\components\espcoredump
C:\Users\jhlee\esp\esp-idf\components\partition_table
C:\Users\jhlee\.espressif\tools\xtensa-esp32-elf\esp-2020r3-8.4.0\xtensa-esp32-elf\bin
C:\Users\jhlee\.espressif\tools\xtensa-esp32s2-elf\esp-2020r3-8.4.0\xtensa-esp32s2-elf\bin
C:\Users\jhlee\.espressif\tools\esp32ulp-elf\2.28.51-esp-20191205\esp32ulp-elf-binutils\bin
C:\Users\jhlee\.espressif\tools\esp32s2ulp-elf\2.28.51-esp-20191205\esp32s2ulp-elf-binutils\bin
C:\Users\jhlee\.espressif\tools\cmake\3.16.4\bin
C:\Users\jhlee\.espressif\tools\openocd-esp32\v0.10.0-esp32-20200709\openocd-esp32\bin
C:\Users\jhlee\.espressif\tools\ninja\1.10.0\
C:\Users\jhlee\.espressif\tools\idf-exe\1.0.1\
C:\Users\jhlee\.espressif\tools\ccache\3.7\
C:\Users\jhlee\.espressif\tools\dfu-util\0.9\dfu-util-0.9-win64
C:\Users\jhlee\.espressif\python_env\idf4.2_py3.8_env\Scripts
C:\Users\jhlee\esp\esp-idf\tools
%PATH%
Checking if Python packages are up to date...
Python requirements from C:\Users\jhlee\esp\esp-idf\requirements.txt are satisfied.

Done! You can now compile ESP-IDF projects.
Go to the project directory and run:
    idf.py build

  • Python export.ps1 대신 직접추가방식변경  
상위 export.ps1의 대신 직접 필요한 부분을 넣어주는 방식으로 변경 
추후 Powershell에서 변경할 일이 있다면 이 방식으로 하도록하자   
$newtemp = "$Env:userprofile\esp\esp-idf\components\esptool_py\esptool;"
$newtemp += "$Env:userprofile\esp\esp-idf\components\app_update;"
$newtemp += "$Env:userprofile\esp\esp-idf\components\espcoredump;"
$newtemp += "$Env:userprofile\esp\esp-idf\components\partition_table;"
$newtemp += "$Env:userprofile\.espressif\tools\xtensa-esp32-elf\esp-2020r3-8.4.0\xtensa-esp32-elf\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\xtensa-esp32s2-elf\esp-2020r3-8.4.0\xtensa-esp32s2-elf\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\esp32ulp-elf\2.28.51-esp-20191205\esp32ulp-elf-binutils\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\esp32s2ulp-elf\2.28.51-esp-20191205\esp32s2ulp-elf-binutils\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\cmake\3.16.4\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\openocd-esp32\v0.10.0-esp32-20200709\openocd-esp32\bin;"
$newtemp += "$Env:userprofile\.espressif\tools\ninja\1.10.0;"
$newtemp += "$Env:userprofile\.espressif\tools\idf-exe\1.0.1;"
$newtemp += "$Env:userprofile\.espressif\tools\ccache\3.7;"
$newtemp += "$Env:userprofile\.espressif\tools\dfu-util\0.9\dfu-util-0.9-win64;"
$newtemp += "$Env:userprofile\.espressif\python_env\idf4.2_py3.8_env\Scripts;"
$newtemp += "$Env:userprofile\esp\esp-idf\tools;"
$newtemp += "$Env:userprofile\.espressif\tools\idf-git\2.30.1\cmd;"
echo $newtemp
 
Set-Item -Path Env:Path -Value ( $newtemp + $Env:Path )    
$Env:Path

pip 와 python은 상위 venv안에 Scripts에 있으므로 이부분만 PATH 넣으면 되는데, PATH 앞에 넣어야, 
우선적으로 다른 Python 보다 먼저 실행되어진다. 

  • Python Path 설정 


3. PowerShell 의 Linux Command 호환 및 세부설정 

Linux에서 많이 사용되어지는 Command들이 Power Shell에서 이제 제공되어지므로 PowerShell Script에 넣어 작성하자. 
다양한 Command들이 지원가능하며, 파이프를 비롯하여 기초적인것은 동작 되어진다.  
Path로 \ 에서 / 로도 호환 동작 과 tee를 비롯하여, redirection도 지원가능하다. 
주의해야 할 것은 옵션이 다르며, 사용법이 조금씩다르므로 주의하도록하며, 업그레이드 될때마다 이게 조금씩 변경되어진다. (주의) 
설마 이전 버전하고 계속 호환성을 유지하겠지~ 

  • Power Shell 에서 제공하는 Linux Command 의 예 (이외 기타등등)
  1. ls
  2. cat 
  3. tee 
  4. echo ( write-host를 좀 더 권장)
  5. cp
  6. rm 
  7. findstr (grep 대신)
  8. mkdir
  9. cd 
  10. tar 
  11. .... 

  • Pipe 기본사용 및 Tee 사용방법  
  1. ls | findstr README*
  2. cat ./build.bat 
  3. cat ./build.bat | tee log.txt 
  4. tar -cvf  test.tar  test0.txt text1.text

Linux만큼 Pipe 기반으로 tee를 이용하여 잘 동작이 안되어지는 것 같다. 점차 나아지겠지~

  • Window Power Shell Script 사용법
재미있는 것은 MS에서도 PS(Power Shell)을 Linux 의 Shell 처럼 비슷하게 지원해주려고 하고 있다. 
(혹시나 해서 , Linux Command 여러번 사용하는데, 의외로 많이 지원해준다) 

  • PowerShell 의 Terminal 색상조절 
Power Shell에서 아래의 색상조절이 안되어서 다른 곳에서 방법을 찾았다. 
다만 Power Shell에서 echo 명령어로는 아무리 해봐도 색상조절 되지 않는 것 같다. 

PS C:\xxx > write-host "hello world" -foregroundcolor "red" 
hello world
PS C:\xxx > write-host "hello world" -foregroundcolor "yellow"      //-ForegroundColor $fgcolor -BackgroundColor $bgcolor
hello world
PS C:\xxx > $colors = [enum]::GetValues([System.ConsoleColor])    //지원되는 Color 및 색상비교를 해볼수 있어 너무 좋다 (Linux 처럼 소리도 되는 지는 추후)
Foreach ($bgcolor in $colors){
    Foreach ($fgcolor in $colors) { Write-Host "$fgcolor|"  -ForegroundColor $fgcolor -BackgroundColor $bgcolor -NoNewLine }
    Write-Host " on $bgcolor"
}

PowerShell Terminal Color 

Linux Terminal Color 코드는 아래 링크 참조 

  • PowerShell 의 Redirection 정보 
Linux 처럼 Rediection이 가능하지만 조금 정보가 다른 것 같다. (e.g. 1> , 2>>)

  • Power Shell Script Function
Function 기능도 제공하므로 좀 복잡하게 구성하고자 할경우 사용하자 

  • PowerShell 관련 전체 Manual
아래에서 전체 Manual을 한번 보도록 하자 
Cmdlet 이 중요한 것 같은데, 아직 개념을 잘 모르겠으며, 원격기능도 제공해준다. 
나의 경우, Bash와 공통분모를 찾아 관련부분만 넣어 사용하려고 한다. 

8/04/2021

Sphinx 기반의 문서정리2 (Doxygen)

1. Sphinx 기본사용법 


Sphinx 기본설치 및 기본사용법 
문서를 처음 5월/6월에 작성했으나, 너무 길어져서 확장하여 8월 분할작성 

Sphinx기반의 ReadTheDoc Hosting
ReadTheDoc Hosting 및 관리가 쉬워서 개인이라면 이방법을 강력추천

Sphinx 와 Github를 연결해보고 사용하겠다고 여러방법으로 테스트 해봤지만, 
가장좋은 것은 현재 ReadtheDoc 사이트에서 Hosting하는게 가장편한 것으로 보인다.  

1.1 Sphinx extension 확장사용 

요즘 Markdown File이 대세이므로, RST파일과 Markdown를 동시에 같이 사용하도록 기능을 확장하도록하자. 
기존에는Markdown은 recommonmark기반으로 사용했다고 하는데, 
myst가 이를 호환해준다고 하고 Sphinx 사이트에서도 이걸로 거의 권장하는 것 같다. 
그리고, 가장 큰 이유는 Github와 호환성때문이다. 


  • markdown 과 mermaid 관련설치
myst_parser만 사용진행 (recommonmakr는 생략사용법은 생략)
(py38-sphinx) $ pip3 install myst_parser
(py38-sphinx) $ pip3 install sphinxcontrib-mermaid  // 옵션이며, extensions 씨 필요없다면 삭제  (간단한 diagram 사용) 

  • mermaid 기본사용법
Mermaid는 Diagram Tool로 오래전부터 Doxygen과 같이 많이 사용되어진  프로그램으로, 가장 많이 사용되는 Tool 이다. 
최근 Github에서도 지원가능하므로, 알아두도록하자 


  • Markdown 관련설정변경 
Markdown 기반으로 하기 위해서 아래와 같이 설정을 변경
(py38-sphinx) $ vi conf.py

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
        'sphinx.ext.autodoc',      # autodoc 안에 automodule 도 포함
        'sphinx.ext.autosummary',  # 현재미사용
        'myst_parser',            # Markdown을 위해서 사용
        'sphinxcontrib.mermaid',  # Mermaid Diagram을 위해서 사용  
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

## 옵션으로 markdown 안에 ::: 되는 것을 동작되기 위해서 설정 RST와 같이 사용가능할것 같음 
## :::{note}
## And here's a note with a colon fence!
## :::
myst_enable_extensions = [
  "colon_fence",
]

## Source Suffix 설정 (rst,md) 
source_suffix = {
    '.rst': 'restructuredtext',
    '.txt': 'restructuredtext',
    '.md': 'markdown',
}


Sphinx-markdown 설치 및 설정 

  • Markdown 예제구성
일반 Markdown이 아닌 RST에서도 사용가능한 기능으로 확장 및 이외 diagram 추가
class에 warning/note/이외 다양한 rst directive 추가가능    
(py38-sphinx) $ vi test1.md
## TEST MD 

Markdown 에서 RST의 directive를 사용해보자  

```{admonition} Here's my note
:class: note

Here's my admonition content 
```

```{admonition} TEST Title
:class: warning

Here's my admonition content 
```

:::{note}
상위에서 설정한 colon fence! 기능 ㅋㅋㅋ
:::


mermaid 사용법임 아래 링크 참조
```{mermaid}
sequenceDiagram
  participant Alice
  participant Bob
  Alice->John: Hello John, how are you?
  loop Healthcheck
      John->John: Fight against hypochondria
  end
  Note right of John: Rational thoughts <br/>prevail...
  John-->Alice: Great!
  John->Bob: How about you?
  Bob-->John: Jolly good!
```
Markdown에서 상위 directive 사용법 

  • Markdown 관련 주의사항
  1. markdown의 # 와 ## 와 ###에 따라 계층이 나누어지므로 조심해서 사용
  2. markdown 외부 Link (http) 동작확인
  3. markdown 내부 Link는 동작확인 (HTML로 자동변경)
  4. markdown 내부 title 링크가 제대로 동작안됨 (*.md->*.html로 변경안됨)

  • index.rst의 재구성 (Markdown 사용)
Markdown을 추가하여 index를 재구성한 후 다시 확인 
(py38-sphinx) $ vi index.rst
.. toctree::
   :maxdepth: 3
   :caption:  Table of Contents
   :numbered:
   
   intro
   test1.md   
   mytest/testa.md
   mytest/testb.md   

(py38-sphinx) $ make clean  //삭제 후 진행 
(py38-sphinx) $ make html   //_build/html/index.html 확인 

index.rst 의 toctree 설정구성 

  • Markdown 상위 결과확인 (Mermaid)
테스트 용으로 Github(Mermaid 지원) 일단 기본으로 동작확인




Github 기반으로 아래와 같이 구성 후 간단히 테스트만 해봤지만, Github의 docs/ 내부는 세부적으로 연결해줘야하는 것 같다.

(py38-sphinx) $ vi index.rst   //Github일 경우 아래 구성으로 구성후 기본테스트만함(불필요한 index 및 다 지움)
.. toctree::
   :maxdepth: 3
   :caption:  Table of Contents
   :numbered:
   
   README.md
              
(py38-sphinx) $ make clean  //삭제 후 진행 
(py38-sphinx) $ make html   //_build/html/index.html 확인 

1.2 Sphinx 의 Output 변경 (Latex/Others) 

HTML 이외의 Output은 구성은 어떻게 되는 지 궁금해서 일단 테스트 진행 
하지만 테스트 결과 HTML만 괜찮은 걸로 보임 

  • 관련 Tool 설치 
(py38-sphinx) $ sudo apt-get install -y latexmk //latexmk 필요   
(py38-sphinx) $ sudo apt-get install texlive-full  //texlive  필요   

  • Latex 설정변경 
Letex 관련설정하여 테스트만 해보고 괜찮게 나오는지만 파악 
(py38-sphinx) $ vi conf.py   // Latex 관련설정추가   

# -- Options for LaTeX output ------------------------------------------------
latex_engine = 'xelatex'
latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    'papersize': 'a4paper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    'preamble': '',

    # Latex figure (float) alignment
    #
    'figure_align': 'htbp',


    # kotex config
    'figure_align': 'htbp',

    'fontpkg': r'''
\usepackage{kotex}
''',
} 

Sphinx Latex 관련설정 및 Font 설정 (출처)
  • Sphinx Builder 로 Output 변경 
(py38-sphinx) $ make latexpdf   // Latex로 출력  
(py38-sphinx) $ make epub   // epub로 출력  
(py38-sphinx) $ make man   // man로 출력  
(py38-sphinx) $ sphinx-build --help  //sphinx-build 사용법확인

일단 한글은 제대로 안되었는데, PDF 파일 뿐만 아니라 다른 Output도 구성이 너무 좋지 않음  

Sphinx의 다양한 output 지원
HTML를 빼고 Theme 및 구성이 제대로 되지 않아 거의 사용안할 듯 


2. Sphinx 와 doxygen 연결  

  • Sphinx 기반의 Doxygen 구성이해(필독)
Python Sphinx 기반의 Doxygen 구성분석 및 필요 Package들 파악 
toctree 예제 및 ESP-IDF이 구성을 자세히 이해할수가 있음 


2.1 ESP32의 Sphinx 와 doxygen 테스트

ESP의 Sphinx가 너무 잘 구현되어있어서, 그것을 그대로 한번 따라 해보려고 했는데, 
버전이 너무 낮아서 아래는 진행하지 않기로 했다. 
나와 같이 삽질하는 사람이 있을 거 같아 기록으로만 남김. 
  • ESP32 의 Sphinx 와 doxygen 사용
sphinx와 doxygen을 TEST을 위해서 기존의  ESP관련부분 참조 
(py38-sphinx) $ cp -a ~/esp/esp-idf/docs espdocs   //esp의 doc를 doxygen으로 만들예정 

(py38-sphinx) $ cd espdocs   //esp의 doc를 doxygen으로 만들예정 

(py38-sphinx) $ pip3 install breathe           //sphinx 와 doxygen 사이의 bridge 역할한다고 함

(py38-sphinx) $ cat requirements.txt 
# This is a list of python packages used to generate documentation. This file is used with pip:
# pip install --user -r requirements.txt
#
# matplotlib is currently required only by the script generate_chart.py
matplotlib==3.3.1 ; python_version>="3"
matplotlib==2.0.1 ; python_version=="2.7"
cairosvg==2.5.1 # required by sphinxcontrib-svg2pdfconverter[CairoSVG]
sphinx==2.3.1
breathe==4.14.1
sphinx-copybutton==0.3.0
sphinx-notfound-page
sphinxcontrib-blockdiag==2.0.0
sphinxcontrib-seqdiag==2.0.0
sphinxcontrib-actdiag==2.0.0
sphinxcontrib-nwdiag==2.0.0
sphinxcontrib-wavedrom==2.0.0
sphinxcontrib-svg2pdfconverter[CairoSVG]==1.1.0
nwdiag==2.0.0
recommonmark
future>=0.16.0 # for ../tools/gen_esp_err_to_name.py
sphinx_selective_exclude==1.0.3
sphinx_idf_theme==0.2.2

(py38-sphinx) $ pip3 install -r requirements.txt   //절대 실행하지 말자. 버전에 전부 너무 아래이며 오래된 package 사용 (venv 다시 설치, 젠장) 
(py38-sphinx) $ python3 build_docs.py   //확실히 기존의 sphinx 구조와 다르며 필요한 것은 다 직접구현 
IDF_PATH로 문제발생 

상위부분은 실패했으며, 분석해서 하려고 했으나 내가 원하는 방향하고 다른 것 같아 여기서 멈춘다 
상위 Sphinx는 ESP-IDF의 Sphinx인데, 너무 오래된 Version의 Sphinx를 사용하고 있다. 
그리고 부족한 부분들의 거의 직접구현하고 연결해서 사용하는 것으로 보인다. 

상위를 진행하면 전부 Version이 Downgrade 되므로 주의 
귀찮아서 기존의 venv를 지우고, 다시 venv 기반으로 sphinx 재설치
상위는 하지말도록하자. 

2.2  Doxygen 과 Sphinx를 Breath 연결구성 

  • ESP Exampel을 이용하여 Doxygen 생성 
일단 C소스가 필요하니, ESP Example을 가져와서 이 기반으로 doxygen을 생성하자. 
관련 package들은 우선 설치를 진행 
(py38-sphinx) $ sudo apt install doxygen     //doxygen 이 없어서 설치 
(py38-sphinx) $ sudo apt install doxygen-latex doxygen-doc  //doxygen 관련 package 설치
(py38-sphinx) $ doxygen-gui graphviz   //오래전부터 graphviz랑 같이사용 

(py38-sphinx) $ mkdir doxydocs   //venv로 이미 설치진행완료 

(py38-sphinx) $ cd doxydocs 

(py38-sphinx) $ cp -a ~/esp/esp-idf/examples  .    //esp32 examples 소스만 가져옴 

(py38-sphinx) $ cmake -version
cmake version 3.16.3

(py38-sphinx) $ doxygen -v
1.8.17 

(py38-sphinx) $ doxygen -g   //Doxyfile 생성 

(py38-sphinx) $ vi Doxyfile    //생성된 Doxyfile 의 설정들을 변경해주자 (소스위치/XML/기타등등)
PROJECT_NAME           = "ESP Sample"
INPUT                  = ./examples 
RECURSIVE              = YES
GENERATE_XML           = YES

(py38-sphinx) $ doxygen       //Doxyfile 기준으로 Doxygen 실행  

(py38-sphinx) $ ls    //html 와 xml 생성확인 HTML을 우선확인해보자  
Doxyfile  examples  html  latex   xml

  • 생성된 Doxygen 구성확인 
  1. 상위 HTML에서 쉽게 생성된 Doxygen 파일 확인 가능 (index.html)
  2. Latex에서는 PDF 파일 확인가능 
  3. XML은 breathe를 위해 사용예정 

나의 경우 Doxygen 자료가 없어서 ESP의 Sample 이용 



  • Sphinx 와 Breathe 기반으로 Doxygen 연결 
Breathe를 기반으로 Doxygen XML을 이용하여 Sphinx 와 연결 

(py38-sphinx) $ mkdir docs
(py38-sphinx) $ cd docs

(py38-sphinx) $ pip3 install breathe           //sphinx 와 doxygen 사이의 bridge 역할한다고 함

(py38-sphinx) $ sphinx-quickstart     //sphinx start 실행  

(py38-sphinx) $ vi conf.py 
## Extension을 위해서 설정 
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

## 만약 Shell Script 형식으로 사용하고자 하면 사용 
#import subprocess
#subprocess.call('make clean', shell=True)
#subprocess.call('cd ../../doxygen ; doxygen', shell=True)

## breathe 설정으로 상위생성된 XML 연결  
breathe_projects = { "ESP Sample": "../xml/" }
breathe_default_project = "ESP Sample"


## Extension에 breathe 추가 및 기타 추가 (필요 없다면 빼자) 
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.mathjax',
    'sphinx.ext.viewcode',
    'sphinx.ext.imgmath',
    'sphinx.ext.todo',
    'breathe',
]

html_theme = 'sphinx_rtd_theme'

(py38-sphinx) $ vi index.rst      // 아래와 같이 설정하면 시간 엄청 오래걸리며 이상하게 생성됨  
.. toctree::
   :maxdepth: 2
   :caption: Contents:

.. doxygenindex::
.. doxygenfunction::
.. doxygenstruct::
.. doxygenenum::
.. doxygentypedef::
.. doxygenclass::

(py38-sphinx) $ make html

  • 결과확인 
비록 ESP의 Sample을 가지고 했지만, 아래와 같이 Doxygen 형태로 나옴




(py38-sphinx) $ vi test0.rst      // @breif 가 있는 함수를 찾아 함수명으로 추출  
C  Functions
-------------

.. doxygenfunction:: ws2812_rmt_adapter

(py38-sphinx) $ vi index.rst      // 확인  
.. toctree::
   :maxdepth: 2
   :caption: Contents:

   test0   
   
(py38-sphinx) $ make html

breathe 기본사용법 


2.3 기타 Doxygen 테스트 

  • Cmake 와 Doxygen 설치 및 확인 

$ cmake -version
cmake version 3.16.3

$ sudo apt install doxygen
$ sudo apt install doxygen-latex doxygen-doc doxygen-gui graphviz 
$ sudo apt install xapian-tools

$ doxygen -v
1.8.17 

https://github.com/jacking75/examples_CMake
git clone https://github.com/ttroy50/cmake-examples.git
//git clone https://github.com/sinairv/Cpp-Tutorial-Samples.git
//$ git clone https://github.com/googleapis/google-cloud-cpp
//$ git clone https://github.com/GoogleCloudPlatform/cpp-samples

https://github.com/GoogleCloudPlatform/python-docs-samples
https://github.com/GoogleCloudPlatform/nodejs-docs-samples
https://github.com/GoogleCloudPlatform/ai-platform-samples


https://breathe.readthedocs.io/en/latest/directives.html#doxygenstruct

$ mkdir docs
$ cd docs
$ doxygen -g   //Doxyfile 생성 

$ vi Doxyfile
PROJECT_NAME           = "Google CPP Sample"
INPUT                  = ../cpp-samples
RECURSIVE              = YES

$ doxygen         // 생성확인


$ cd ..
$ ls 
cpp-samples  docs  py38-sphinx

$ find . -name CMakeLists.txt
./cpp-samples/gcs-fast-transfers/CMakeLists.txt
./cpp-samples/iot/mqtt-ciotc/CMakeLists.txt
./cpp-samples/cloud-run-hello-world/CMakeLists.txt
./cpp-samples/populate-bucket/CMakeLists.txt
./cpp-samples/speech/api/CMakeLists.txt
./cpp-samples/gcs-indexer/CMakeLists.txt


$ vi CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
project ("Sphinx Example")
add_subdirectory ("Cpp-Tutorial-Samples")
add_subdirectory ("docs")

$ vi docs/CMakeLists.txt
find_package(Doxygen REQUIRED)

#This will be the main output of our command
set(DOXYGEN_INDEX_FILE ${CMAKE_CURRENT_SOURCE_DIR}/html/index.html)

add_custom_command(OUTPUT ${DOXYGEN_INDEX_FILE}
                   DEPENDS ${CAT_CUTIFIER_PUBLIC_HEADERS}
                   COMMAND ${DOXYGEN_EXECUTABLE} Doxyfile
                   WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
                   MAIN_DEPENDENCY Doxyfile
                   COMMENT "Generating docs")

add_custom_target(Doxygen ALL DEPENDS ${DOXYGEN_INDEX_FILE})

$ vi docs/Doxyfile.in
#...
INPUT = "@DOXYGEN_INPUT_DIR@"
#...
OUTPUT_DIRECTORY = "@DOXYGEN_OUTPUT_DIR@"
#...

$ vi docs/CMakeLists.txt
find_package(Doxygen REQUIRED)

set(DOXYGEN_INPUT_DIR ${PROJECT_SOURCE_DIR}/cpp-samples)
set(DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/docs/doxygen)
set(DOXYGEN_INDEX_FILE ${DOXYGEN_OUTPUT_DIR}/html/index.html)
set(DOXYFILE_IN ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in)
set(DOXYFILE_OUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)

#Replace variables inside @@ with the current values
configure_file(${DOXYFILE_IN} ${DOXYFILE_OUT} @ONLY)

file(MAKE_DIRECTORY ${DOXYGEN_OUTPUT_DIR}) #Doxygen won't create this for us
add_custom_command(OUTPUT ${DOXYGEN_INDEX_FILE}
                   DEPENDS ${CAT_CUTIFIER_PUBLIC_HEADERS}
                   COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYFILE_OUT}
                   MAIN_DEPENDENCY ${DOXYFILE_OUT} ${DOXYFILE_IN}
                   COMMENT "Generating docs")

add_custom_target(Doxygen ALL DEPENDS ${DOXYGEN_INDEX_FILE})

$ cmake -Btest
$ cmkae --build test
$ cmake CMakeLists.txt

$ vi cpp-samples/CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
project ("Google Sample")

add_subdirectory ("gcs-fast-transfers")
add_subdirectory ("iot/mqtt-ciotc")
add_subdirectory ("cloud-run-hello-world")
add_subdirectory ("populate-bucket")
add_subdirectory ("speech/api")
add_subdirectory ("gcs-indexer")



$ sudo apt-get install lynx    // HTML viewer로 설치했으나, 너무 좋지않아 필요없음 


bazel 사용법


Github Page 설정관련 (Web 관련부분)

RST 와 Markdown

Github 기반으로 Technical 관련문서를 만드는 사이트 

Github기반으로 Sphinx로 이용하여 문서만드는 예제 


8/01/2021

Sphinx 기반의 문서정리-1

1. Sphinx 설치 

  • Python venv기반으로 구성 
호환성문제로 virtualenv를 사용하기로 결정했으며, 상위참조하여 생성 
$ python -V  //python이 없다면 /us/bin 에서 확인 후 설치 
Python 3.8.5
# sudo ln -s /usr/bin/python3 /usr/bin/python   //나의 경우 이전에 python2를 python 심볼링크 사용 (옵션) 
# sudo apt-get install python3-venv     //venv 설치 (옵션)

$ mkdir works
$ cd works
$ python -m venv py38-sphinx      //py38-sphinx venv 생성

$ ls
py38-sphinx

$ ls py38-sphinx/bin/           //python 과 python3 는 symbollink 확인 
Activate.ps1  activate  activate.csh  activate.fish  easy_install  easy_install-3.8  pip  pip3  pip3.8  python  python3

$ source py38-sphinx/bin/activate   //virtual env의 python 사용 
매번 py38-sphinx 내부의 virtualenv를 사용하기위해서는 source를 진행하거나, .bashrc 등 기타 로그인때 자동으로 설정해도 된다.


  • venv 안에 Python package 설치 
sphinx package 설치 및 확인 
(py38-sphinx) $ pip list
Package       Version
------------- -------
pip           20.0.2 
pkg-resources 0.0.0  
setuptools    44.0.0 

(py38-sphinx) $ pip install sphinx   //venv에 sphinx 설치

(py38-sphinx) $ pip list
Package                       Version  
----------------------------- ---------
alabaster                     0.7.12   
Babel                         2.9.1    
certifi                       2021.10.8
charset-normalizer            2.0.7    
docutils                      0.17.1   
idna                          3.3      
imagesize                     1.2.0    
Jinja2                        3.0.2    
MarkupSafe                    2.0.1    
packaging                     21.0     
pip                           20.0.2   
pkg-resources                 0.0.0    
Pygments                      2.10.0   
pyparsing                     2.4.7    
pytz                          2021.3   
requests                      2.26.0   
setuptools                    44.0.0   
snowballstemmer               2.1.0    
Sphinx                        4.2.0    
sphinxcontrib-applehelp       1.0.2    
sphinxcontrib-devhelp         1.0.2    
sphinxcontrib-htmlhelp        2.0.0    
sphinxcontrib-jsmath          1.0.1    
sphinxcontrib-qthelp          1.0.3    
sphinxcontrib-serializinghtml 1.1.5    
urllib3                       1.26.7 

(py38-sphinx) $ pip list | wc -l    //전부 28 line 이며 -2개를 하면 26 package 가지고 있음(계산하기 귀찮음) 
28

(py38-sphinx) $ pip list | wc      //newline:28  word:56  byte counts:1120
     28      56    1120


Python venv 기본사용법



1.1. sphinx 기본 테스트

  • Sphinx 기본사용 및 확인 

(py38-sphinx) $ mkdir docs
(py38-sphinx) $ cd docs

(py38-sphinx) $ sphinx-quickstart  // 실행하면, 현재 directory기준 
Sphinx 4.0.2 빠른 시작 유틸리티에 오신 것을 환영합니다.

다음 설정에 대한 값을 입력하십시오 (대괄호로 묶여 있는 기본값이 존재하고
이 값을 사용하려면 바로 Enter를 누릅니다).

선택한 루트 경로: .

Sphinx 출력을 위한 빌드 디렉토리를 배치하는 두 가지 옵션이 있습니다.
루트 경로 내에서 "_build" 디렉토리를 사용하거나, 루트 경로 내에서
"source"와 "build" 디렉토리로 분리합니다.
> 원본과 빌드 디렉토리 분리 (y/n) [n]:
> 프로젝트 이름: testSphinx
> 작성자 이름: Jeonghun Lee
> 프로젝트 릴리스 []: 1.0

문서를 영어 이외의 언어로 작성하려는 경우, 여기에서 해당 언어 코드로 언어를
선택할 수 있습니다. 그러면 Sphinx가 생성한 텍스트를 해당 언어로 번역합니다.

지원되는 코드 목록은
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language
를 참조하십시오.
> 프로젝트 언어 [en]:
/home/jhlee/works/docs/conf.py 파일을 만드는 중입니다.
/home/jhlee/works/docs/index.rst 파일을 만드는 중입니다.
/home/jhlee/works/docs/Makefile 파일을 만드는 중입니다.
/home/jhlee/works/docs/make.bat 파일을 만드는 중입니다.

완료됨: 초기 디렉토리 구조가 생성되었습니다.

이제 마스터 파일 /home/jhlee/works/docs/index.rst을(를) 채우고 다른 원본 문서 파일을 만들어야 합니다. Makefile을 사용하여 다음과 같이 문서를 빌드하십시오:
   make builder
여기서 "builder"는 지원되는 빌더 중 하나(예: html, latex, linkcheck)입니다.

(py3-sphinx) $ ls      // 원본과 빌드 디렉토리 분리 [n] 일경우 구성 
Makefile  _build  _static  _templates  conf.py  index.rst  make.bat


(py38-sphinx) $ ls      // 원본과 빌드 디렉토리 분리 [y] 일경우 구성 
Makefile  build  make.bat  source 
(py3-sphinx) $ ls source
_static  _templates  conf.py  index.rst

(py3-sphinx) $ make html   //_build 안에 html 안에 html구성 index.html 확인

  • _build/html/index.html
상위내용 및 venv 기반의 sphinx 설정 
  https://www.docslikecode.com/learn/01-sphinx-python-rtd/

1.2. Sphinx의 theme 변경 

Sphinx에서 제공하는 Theme들을 찾아 설치 후 이를 설정하고 이 기반으로 변경해보자.
아래는 ReadTheDoc의 theme이며, 이외에도 많으므로 각 설정해보면서 바꾸어 보자.


(py38-sphinx) $ pip install sphinx_rtd_theme      //sphinx theme 설치 esp32는 별도로 변경해서 사용함
(py38-sphinx) $ pip list | wc                     //sphinx_rtd_theme 만 설치됨
     29      58    1160

(py38-sphinx) $ vi conf.py   //sphinx_rtd_theme 만 변경
#html_theme = 'alabaster'
html_theme = 'sphinx_rtd_theme'

(py3-sphinx) $ make html   //_build 안에 html 안에 html구성 index.html 확인

  • _build/html/index.html


Sphinx는 이외에도 다양한 Theme을 제공
아래사이트에서 본인이 원하는 Theme 찾고 설치진행 후 상위와 동일하게 설정 



1.3. Sphinx extension 설정 (conf.py)

  • sphinx에서 필요한 기능을 확장하여 설정
  1. extension 기능을 사용하기 위해서 아래와 같이 python 소스의 주석을 제거한 후 진행 
  2. 원하는 extension 기능을 아래와 같이 추가 
(py38-sphinx) $ vi conf.py   //각 관련부분 수정 
## 아래부분은 기본으로 주석으로 되어짐 
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

## 확장기능으로 아래 링크참조 
extensions = [
        'sphinx.ext.autodoc',      # autodoc 안에 automodule 도 포함
        'sphinx.ext.autosummary',  # 현재미사용 
]
## 이전설정으로 다른 Theme으로 변경가능 
html_theme = 'sphinx_rtd_theme'

extension을 이용하여 다양하게 확장가능
상위에 각각의 링크확인가능 


1.4. Sphinx 의 index.rst 설정 


  • index.rst 파일설정 
index.rst 기본값 확인 후 toctree 설정진행 
(py38-sphinx) $ cat index.rst   //기본설정확인
Welcome to testSphinx's documentation!
======================================

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


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

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

각 구성할 *.rst 파일과 함께 최종 index.rst 에 연결진행 

  • about.rst 구성 
(py38-sphinx) $ vi about.rst    //상위에서 source 와 build를 분리하지않음 (분리하면 source 안에)
about 
=====

about 에대한 파일이며 이것은 오직 테스트용으로 사용함 

.. math::
   
   (a + b)^2 = a^2 + 2ab + b^2

   (a - b)^2 = a^2 - 2ab + b^2




  • intro.rst 구성 
(py38-sphinx) $ vi intro.rst  //아래내용들은 toctree 예제참조
intro^^
=========

정말 이게 인트로인지 테스트 해보자 

.. note::

   This function is not suitable for sending spam e-mails.

.. versionadded:: 2.5
   The *spam* parameter.


.. deprecated:: 3.1
   Use :func:`spam` instead.


.. seealso::

   Module :py:mod:`zipfile`
      Documentation of the :py:mod:`zipfile` standard module.

   `GNU tar manual, Basic Tar Format ???
      Documentation for tar archive files, including GNU tar extensions.   




  • source.rst
(py38-sphinx) $ vi source.rst
Python source 
==============

.. automodule:: pysrc.testclass
    :members: 
    
(py38-sphinx) $ mkdir pysrc    
(py38-sphinx) $ vi pysrc/testclass.py  //아래사이트에서 얻은예제 추가 (상위 conf.py 확장) 
"""
    My Module
    ~~~~~~~~~
"""

class Test(object):
    """두 개의 int 값을 입력받아 다양한 연산을 할 수 있도록 하는 클래스.

    :param int a: a 값
    :param int b: b 값
    """

    def __init__(self, a, b):
        self._a = a
        self._b = b

    def is_same(self):
        """미리 입력받은 a와 b값이 같은지 확인하여 결과를 반환합니다.

        :return: boolean True or False에 대한 결과, a와 b가 값으면 True, 다르면 False

        예제:
            다음과 같이 사용하세요:

            >>> Test(1, 2).is_same()
            False

        """
        return self._a == self._b

    def plus(self):
        """미리 입력받은 a와 b값을 더한 결과를 반환합니다.

        :returns: int a + b에 대한 결과

        예제:
            다음과 같이 사용하세요:

            >>> Test(2, 1).plus()
            3


        """
        return self._a + self._b




  • index.rst 변경 
(py38-sphinx) $ vi index.rst   //상위에서 추가한 *rst 파일들 추가 혹은 directory 추가 
Welcome to my Sphinx TEST !!!!!!!!!!!!
======================================

This is the documentation for TEST 
is it ok???   
한글도 되는 지 테스트를 해보도록하자 ㅋㅋㅋㅋㅋ   
MarkDown 과 유사하지만 "toctree" 별도로 제어로사용??   

.. toctree::
   :maxdepth: 2
   :caption: Table of Contents
   :numbered:   

   about
   intro
   source

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

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


(py3-sphinx) $ make html   //_build 안에 html 안에 html구성 index.html 확인 

  • 결과확인 
상위설정 후 make html로 생성된 파일확인 






상위 sphinx quickstart 기본설명
  https://www.sphinx-doc.org/en/master/usage/quickstart.html