soma0sd

코딩 & 과학 & 교육

Python: VSCODE의 tasks.json를 이용한 프로젝트 감시

반응형

VSCODE(Visual Studio Code;비주얼 스튜디오 코드) 프로젝트 안의 파일이 변경, 생성되는 경우 자동으로 변경내용을 포함하여 새로 빌드하는 것을 감시(Watch)라고 합니다. 웹 개발 등에서 감시를 활용하면 매번 변경사항을 적용하기 위해 컴파일 명령을 사용하지 않을 수 있으니 편리합니다. VSCODE의 플러그인인 tsc-watchSASS-autocompile등이 이런 기능을 제공하고 있습니다.

이 포스트는 tasks.json을 활용하여 감시 기능을 하는 파이썬(Python) 스크립트를 사용하는 방법을 다룹니다.

tasks.json

프로젝트의 .vscode/tasks.json은 테스크 작업을 관리하는 파일입니다. Ctrl + Shift + P를 눌러 작업 명령 팔레트를 열어 Tasks: Configure Task 명령을 사용하여 초기화 되어있는 파일을 얻을 수 있습니다.

{
"version": "2.0.0",
  "tasks": [
    {
      "type": "typescript",
      "tsconfig": "_ts\\tsconfig.json",
      "option": "watch"
    }
  ]
}

watchdog 패키지

파이썬을 통해 프로젝트를 감시하는 작업을 손쉽게 해주는 watchdog 패키지를 활용해 스크립트를 작성합니다. 표준 패키지가 아니기 때문에 패키지를 따로 설치해야 합니다.

pip install watchdog

아나콘다(anaconda)를 사용하는 경우,

conda install -c conda-forge watchdog 

python 컴파일 스크립트 작성

예시로 사용하는 스크립트는 HTML 문서의 <include /> 태그 위치에 해당하는 HTML내용을 붙여넣습니다.
예시를 참고하여 파일 변경시 작동할 스크립트를 작성합니다.

import time
import re
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

root_dir = "./_html/"  # html 템플릿과 조각파일이 들어있는 상대경로
root_html = "skin.html" # 템플릿 파일

out_html = "./dist/skin.html" # 결과물을 저장할 위치


def sub_text(src):
  # 불러오는 파일 내용을 리턴
  # 파일이 없는 경우 빈 문자열 리턴
  try:
    with open(root_dir + src) as f:
      return f.read()
  except:
    return ''

class EventHandler(FileSystemEventHandler):
  # 파일 변경 이벤트 핸들러
  def on_any_event(self, event):
    print(f'{event.event_type} : {event.src_path}')
    rex1 = r'<include.+?src="(?P<src>.+?)".*?>'
    with open(root_dir + root_html,'r',encoding='utf8') as root_file:
      base = root_file.read()
    rex_include = re.compile(rex1)
    m = rex_include.search(base)
    while m:
      base = base.replace(m.group(), sub_text(m.group('src')))
      m = rex_include.search(base)
    with open(out_html, 'w', encoding='utf8') as f:
      f.write(base)

if __name__ == "__main__":
  event_handler = EventHandler()
  observer = Observer()
  observer.schedule(event_handler, path=root_dir, recursive=True)
  observer.start()

  try:
    while True:
      time.sleep(1)
  except KeyboardInterrupt:
    observer.stop()
  observer.join()

빌드 테스크 등록

웹 개발을 하다보면 여러 테스크를 사용하는 경우가 종종 생깁니다. 테스크 단위로 사용하는 것은 명령어를 일일히 입력하는 것 보단 확실히 편하지만 매번 프로젝트를 처음 시작할 때마다 테스크를 사용하는 것도 금방 귀찮아지죠.

여러 테스크를 묶어 하나의 빌드 테스크로 만든 뒤 Ctrl + Shift + B 키를 눌러 한번에 실행하는 방법이 있습니다. 아래의 tasks.json을 참조하여 작성하시면 됩니다.

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "HTML_Watch",
      "type": "shell",
      "command": "python ./bin/html_watch.py"
    },
    {
      "label": "typescript_Watch",
      "type": "typescript",
      "tsconfig": "_ts\\tsconfig.json",
      "option": "watch",
      "problemMatcher": [
        "$tsc-watch"
      ]
    },
    {
      "label": "Build",
      "dependsOn": [
        "typescript_Watch",
        "HTML_Watch"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

이 예시는 위의 파이썬 감시 스크립트 테스크와 타입스크립트를 감시하는 테스크를 한번에 묶어 기본 빌드 테스크로 만든 것입니다. Ctrl + Shift + B 를 누르면 자동으로 터미널을 통해 해당 테스크를 진행합니다.

반응형
태그:

댓글

End of content

No more pages to load