GuriLogs.

Custom Python Package 생성하기 본문

Python

Custom Python Package 생성하기

guri-sh 2024. 5. 26. 16:52

먼저, Python Package 구조 생성

├── custom_python
│   ├── __init__.py
│   └── functions.py
├── README.md
└── setup.py

패키지 내에서 활용하고 싶은 함수 정의

custom_python/functions.py 파일에 정의

여기서 functions는 import custom_python.functions 이렇게 활용됨.

 

def info(~):
  ...
  return ...
def funct(~):
  ...
  return ...
등등

빌드 정보 세팅

setup.py 파일을 생성하고 해당 파일 안에 빌드 정보를 입력한다.

setup에는 이 외에도 많은 파라미터가 있다.(https://setuptools.pypa.io/en/latest/references/keywords.html)

from setuptools import setup

setup(name='custom_python',
      version='0.1',
      description='databricks functions for datacube',
      author='Guri',
      author_email='guri@guri',
      license='MIT',
      python_requires='>=3.6',
      packages=['custom_python'])

 

빌드 모듈 설치

pip3 install wheel
pip3 install setuptools

 

빌드

python3 setup.py bdist_wheel

빌드 후 구조

├── build
│   ├── bdist.macosx-12-arm64
│   └── lib
│       └── custom_python
│           ├── __init__.py
│           └── functions.py
├── dist
│   └── custom_python-0.1-py3-none-any.whl
├── datacube_python
│   ├── __init__.py
│   └── functions.py
├── README.md
├── setup.py
└── custom_python.egg-info
    ├── dependency_links.txt
    ├── PKG-INFO
    ├── SOURCES.txt
    └── top_level.txt

여기서 dist/custom_python-0.1-py3-none-any.whl 파일을 활용할 것이다.

python wheel file name은 {distribution}-{version}(-{build tag})?-{python tag}-{abi tag}-{platform tag}.whl 이어야 한다.
안그러면 인식을 못함.. 참고 ) https://peps.python.org/pep-0427/#file-name-convention

 

wheel 파일 설치 방법

pip install custom_python-0.1-py3-none-any.whl

 

 

 

setup.py를 직접 호출하지 않고 빌드하는 방법

위에서는 setup.py를 바로 호출하여 패키지를 생성했지만, 아래 글을 확인해보면 직접 호출하는 것을 지양하라고 한다.

python build 명령어는 setup.py 파일이 존재하는 경우, 해당 파일을 빌드한다.

python -m build

 

GHA로 빌드 자동화

  • 특정 폴더 내의 파일이 변경되었을 때, GHA 실행 (on/push/paths/ 하위 내용)
  • setup.py 파일이 있는 경로로 이동하여 python -m build 실행
name : build_python_package
on:
  push:
    paths:
      - '_custom_python_packages/**'
    branches:
      - main
  workflow_dispatch:

jobs:
  build_custom_python_package:
    runs-on: [ self-hosted ]
    steps:
      #----------------------------------------------
      # check-out repo
      #----------------------------------------------
      - name: Check out repository
        uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.12'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install --upgrade build
          pip install setuptools wheel
      - name: Build and publish
        run: |
          cd _custom_python_packages
          python -m build
      #----------------------------------------------

 

참고자료