PyPI에 커맨드 라인 프로그램 퍼블리싱하기

폐쇄맨·2020년 6월 24일
0

Python

목록 보기
1/1
post-thumbnail

PyPI는 파이썬 패키지 리포지토리이다. 이 덕분에 우리가 pip 커맨드로 원하는 패키지를 설치할 수 있다. PyPI에 접속해서 계정을 만들면 본인이 직접 만든 커맨드 라인 프로그램을 퍼블리싱할 수 있다. 회원가입 후 이메일 인증을 하면 다시 접속하지 않으니 홈페이지는 종료한다.
물론 이전에 배포할 커맨드라인 프로그램을 만드는 것이 우선이다. 나는 내가 만든 간단한 계산기 프로그램인 bambic을 사용할 것이다.

Configure Package

setup.py 파일을 통해 배포하려는 패키지의 기본적인 정보를 적어야한다. 프로젝트 최상위 폴더에 setup.py를 만들고 에디터를 열어 아래의 코드를 적어보자. 참고로 아래의 코드는 이곳에서 발췌한 것이다.

# setup.py
from setuptools import setup, find_packages
from io import open
from os import path
import pathlib

# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text()

# automatically captured required modules for install_requires in requirements.txt and as well as configure dependency links
with open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as f:
    all_reqs = f.read().split('\n')
    
install_requires = [x.strip() for x in all_reqs if ('git+' not in x) and (
    not x.startswith('#')) and (not x.startswith('-'))]
    
dependency_links = [x.strip().replace('git+', '') for x in all_reqs \
                    if 'git+' not in x]

README.md 파일의 내용을 문자열로 변환하고, 디펜던시 링크를 생성하고, requirements.txt에서 필요한 모듈을 캡쳐했다.

requirements.txt은 가상환경에서 개발중이라면 다음의 커맨드로 생성가능하다.

pip freeze > requirements.txt

아니면 그냥 직접 적는다.

click
click-command-tree
click-help-colors
click-plugins

setup.py에 뒤이어 아래의 코드를 적는다. 위와 같은 블로그에서 발췌했다.

from setuptools import setup, find_packages
from io import open
from os import path
import pathlib

# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text()

# automatically captured required modules for install_requires in requirements.txt and as well as configure dependency links
with open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as f:
    all_reqs = f.read().split('\n')

install_requires = [x.strip() for x in all_reqs if ('git+' not in x) and (
    not x.startswith('#')) and (not x.startswith('-'))]

dependency_links = [x.strip().replace('git+', '') for x in all_reqs \
                    if 'git+' not in x]

setup (
    name = 'bambic',
    description = 'WeCode 11th Bambi\'s second challenge of python programming',
    version = '0.1.1',
    packages = find_packages(), # list of all packages
    install_requires = install_requires,
    python_requires='>=3.7', 
    entry_points='''
            [console_scripts]
            bambic=bambic.__main__:main
    ''',
    author="Choonghee Lee",
    keyword="cli-calculator, WeCode, bambic, calculator",
    long_description=README,
    long_description_content_type="text/markdown",
    license='MIT',
    url='https://github.com/choonghee-lee/cli-calculator',
    download_url='https://github.com/choonghee-lee/cli-calculator/archive/master.zip',
    dependency_links=dependency_links,
    author_email='test@email.com',
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.7",
    ]
)

위의 코드에서 여러가지 옵션을 사용하였다. setuptools 문서에서 자세한 사항을 확인할 수 있다. 여기서는 옵션을 간단히 알아본다.

  1. name: PyPI에 보이는 패키지 이름
  2. version: 패키지의 현재 버전
  3. packages: 소스코드가 담고있는 패키지와 서브 패키지를 의미한다. find_packages 모듈을 사용하여 자동으로 서브 패키지를 찾도록 한다.
  4. install_requires: 나의 패키지에 필요한 서드 파티 라이브러리 또는 디펜던시들을 적는다. setup.py의 상단 부분에 requirements.txt를 읽는 부분을 참조한다.
  5. entrypoints: 본인의 패키지의 엔트리 포인트이다. 여기서는 _bambic 폴더의 __main.py__main()으로 지정되어 있다.

패키지를 PyPI에 퍼블리싱하기 전에, 문서를 제공해야하는데 README.md 또는 Readme.rst 파일 등을 제공해야한다.

패키지 퍼블리싱과 상관없지만 .gitignore도 설정하자!

PyPI에 퍼블리싱하기

이제 퍼블리싱을 위한 준비는 끝났다. 맨 처음 PyPI에서 생성한 계정과 패스워드를 기억하고 있으면 된다. 그리고 Twine을 설치한다. PyPI에 나의 패키지를 업로드를 할 수 있게 도와주는 도구이다.

pip install twine

먼저 로컬에서 패키지를 테스트한다.

python setup.py install

잘 실행되는 확인해보자.

# entry_point [options] command ...
bambic --version

빌드를 한다.

python setup.py sdist bdist_wheel

그러면 다음과 같은 파일들이 dist 디렉토리에 생성된다.

dist/
    ├── bambic-0.1.1-py3-none-any.whl
    └── bambic-0.1.1.tar.gz

드디어 배포한다.

twine upload dist/*

직접 설치해본다.

pip install bambic

직접 홈페이지에서 확인해보자. https://pypi.org/project/ 에서 직접 본인의 패키지를 검색해본다. Project description에 README.md 파일이 적용된 것을 볼 수 있다.

결론

참고했던 블로그를 중심으로 어찌저찌 퍼블리싱을 하긴 했다. 모듈을 여러개 만들어서 배포하고 싶었는데 잘되지 않아서 하나의 모듈로 합쳐서 배포했다. 내일 찾아봐야겠다.

profile
폐쇄맨

1개의 댓글

comment-user-thumbnail
2021년 6월 27일

안녕하세요. 본 튜토리얼을 따라 했는데 터미널 상에서 package_name -u optionU 형태로 사용하려면 어떤 옵션을 추가해주어야 할까요?

정확히는 bambic --version 이 부분을 따라하는데 실패했습니다

답글 달기