Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기 [링크 복사], [링크+제목 복사]
조회: 6988
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
; https://www.sysnet.pe.kr/2/0/12863

개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
; https://www.sysnet.pe.kr/2/0/12865

개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
; https://www.sysnet.pe.kr/2/0/12867

개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
; https://www.sysnet.pe.kr/2/0/12870




파이썬 - PyPI 패키지 만들기

닷넷의 NuGet처럼, 파이썬에는 PyPI 저장소가 있는데요, 바로 그곳에 파이썬으로 만든 패키지(흔한 말로 라이브러리)를 올리는 실습을 해보겠습니다.

Find, install and publish Python packages with the Python Package Index
; https://pypi.org/

등록할 패키지는 테스트 삼아 간단하게 다음의 코드로 합니다.

# iputil.py

import requests


def get():
    """
    Get my Public IP in Python
    ; https://pytutorial.com/python-get-public-ip
    :return:
    """
    endpoint = 'https://ipinfo.io/json'
    response = requests.get(endpoint, verify=True)

    if response.status_code != 200:
        return 'Status:', response.status_code, 'Problem with the request. Exiting.'
        exit()

    data = response.json()

    return data['ip']


if __name__ == '__main__':
    print(get())

그리고 편의상 위의 코드를 담은 파일을 프로젝트 루트의 하위에 디렉터리를 하나 만들어 그 안에 패키지로 묶일 파일들을 담아 둘 텐데요, 가령 "netutil" 이름의 디렉터리를 만들고 그 안에 위의 코드를 담은 "iputil.py" 파일과, 패키지임을 알리는 __init__.py를 위치시킵니다.

# __init__.py

from netutil import iputil

__version__ = '1.0.0.1'
__author__ = 'techshare'

이와 함께 setup.py를 프로젝트의 루트 디렉터리에 생성하는데요, 따라서 대략 다음과 같은 구조가 됩니다.

.
├── netutil
│   ├── __init__.py
│   └── iputil.py
└── setup.py

그리고 setup.py는 다음의 코드를 담습니다.

from setuptools import setup, find_packages
import netutil


setup(
    name="net-util",
    description="utility functions for networking",
    version=netutil.__version__,
    author=netutil.__author__,
    author_email="techsharer@outlook.com",
    url="https://www.sysnet.pe.kr",
    license="Ms-PL",
    packages=find_packages(exclude=[]),
    install_requires=["requests>=2.22.0"],
)

자, 그럼 여기까지 해서 오류가 없음을 다음의 명령어로 테스트해 줍니다.

c:\temp> python setup.py
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: no commands supplied

setup.py에 문제가 없다면 위와 같은 식의 출력이 나와야 합니다.




"python setup.py" 명령어의 출력에도 나오지만, 필요한 cmd 인자가 하나 더 있습니다. 이것은 "--help-commands"를 주면 알 수 있는데, 여러 가지 명령어 중에 여기서는 bdist_wheel을 사용합니다.

c:\temp> python setup.py bdist_wheel
running bdist_wheel
running build
running build_py
creating build
creating build\lib
creating build\lib\netutil
copying netutil\iputil.py -> build\lib\netutil
copying netutil\__init__.py -> build\lib\netutil
installing to build\bdist.win-amd64\wheel
running install
running install_lib
creating build\bdist.win-amd64
creating build\bdist.win-amd64\wheel
creating build\bdist.win-amd64\wheel\netutil
copying build\lib\netutil\iputil.py -> build\bdist.win-amd64\wheel\.\netutil
copying build\lib\netutil\__init__.py -> build\bdist.win-amd64\wheel\.\netutil
running install_egg_info
running egg_info
creating net_util.egg-info
writing net_util.egg-info\PKG-INFO
writing dependency_links to net_util.egg-info\dependency_links.txt
writing top-level names to net_util.egg-info\top_level.txt
writing manifest file 'net_util.egg-info\SOURCES.txt'
reading manifest file 'net_util.egg-info\SOURCES.txt'
writing manifest file 'net_util.egg-info\SOURCES.txt'
Copying net_util.egg-info to build\bdist.win-amd64\wheel\.\net_util-1.0.0.0-py3.7.egg-info
running install_scripts
creating build\bdist.win-amd64\wheel\net_util-1.0.0.0.dist-info\WHEEL
creating 'dist\net_util-1.0.0.0-py3-none-any.whl' and adding 'build\bdist.win-amd64\wheel' to it
adding 'netutil/__init__.py'
adding 'netutil/iputil.py'
adding 'net_util-1.0.0.0.dist-info/METADATA'
adding 'net_util-1.0.0.0.dist-info/WHEEL'
adding 'net_util-1.0.0.0.dist-info/top_level.txt'
adding 'net_util-1.0.0.0.dist-info/RECORD'
removing build\bdist.win-amd64\wheel

그럼, 현재 디렉터리 기준으로 하위에 "build", "dist", "[setup.py에 지정한 name].egg-info" 디렉터리가 생성이 되는데 최종 결과물은 "dist" 하위에 생성되고, 예제의 경우 "net_util-1.0.0.0-py3-none-any.whl"이 됩니다. (그동안, 패키지 관리자를 사용해 보셨다면 whl 파일도 결국 zip 파일임을 예상할 수 있을 것입니다. ^^)




whl 파일(PEP 427 The Wheel Binary Package Format 1.0)은 최종 패키징 파일이기 때문에 이것 자체로 pip을 이용한 설치가 가능합니다.

c:\temp\dist> pip install net_util-1.0.0.0-py3-none-any.whl
Processing c:\temp\dist\net_util-1.0.0.0-py3-none-any.whl
Requirement already satisfied: requests>=2.22.0 in e:\python37\lib\site-packages (from net-util==1.0.0.0) (2.26.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in e:\python37\lib\site-packages (from requests>=2.22.0->net-util==1.0.0.0) (1.26.6)
Requirement already satisfied: charset-normalizer~=2.0.0 in e:\python37\lib\site-packages (from requests>=2.22.0->net-util==1.0.0.0) (2.0.4)
Requirement already satisfied: certifi>=2017.4.17 in e:\python37\lib\site-packages (from requests>=2.22.0->net-util==1.0.0.0) (2021.5.30)
Requirement already satisfied: idna<4,>=2.5 in e:\python37\lib\site-packages (from requests>=2.22.0->net-util==1.0.0.0) (3.2)
Installing collected packages: net-util
Successfully installed net-util-1.0.0.0

이후, 다른 파이썬 프로젝트에서 다음과 같이 import시켜 사용할 수 있습니다.

import netutil

print(netutil.iputil.get_public_ip())

사실 로컬에서 사용할 거라면 (develop mode를 지원하는) "pip install -e ." 등의 방법을 사용하는 것이 더 편리하지만, 그래도 복잡한 setup.py를 구성한 경우 정상적으로 동작하는지 저런 식으로 테스트하는 것도 좋겠습니다.

자, 그럼 제대로 setup.py가 동작했다면 이제 결과물을 PyPI에 올려야 할 텐데요, 재미있는 것은 PyPI의 경우 직접 패키징 파일을 업로드하는 기능이 사이트에서 제공하지 않습니다. (제가 못 찾은 걸 수도 있습니다. ^^;)

대신, twine과 같은 식의 도구를 사용해 다음과 같이 등록할 수 있습니다.

c:\temp> pip install twine

C:\temp> twine upload dist/net_util-1.0.0.0-py3-none-any.whl
Uploading distributions to https://upload.pypi.org/legacy/
Enter your username: techshare
Enter your password:
Uploading net_util-1.0.0.0-py3-none-any.whl
100%|███████████████████████████████████████████████| 4.51k/4.51k [00:01<00:00, 2.46kB/s]

View at:
https://pypi.org/project/net-util/1.0.0.0/

그런데, 저렇게 실행 시 계정 정보를 입력받는 것이 영 못마땅한데요, 다행히 별도 설정 파일을 이용하는 방법도 있습니다.

[윈도우]
%USERPROFILE%\.pypirc

[리눅스]
$HOME/.pypirc

환경에 따라 위의 경로로 ".pypirc" 파일을 만들고 그 안에 계정 정보를 넣어두면,

[pypi]
  username = ...사용자 계정...
  password = ...사용자 암호...

twine 실행 시 계정 정보를 묻지 않습니다. 하지만, 그래도 여전히 "사용자 암호"가 노출되는데, 이러한 문제는 PyPI 사이트로부터 "API 토큰"을 생성하는 것으로 해결할 수 있습니다.

pypi_api_token_1.png

토큰 값은 한 번만 출력되므로 페이지를 벗어나기 전에 반드시 복사해 두어야 합니다. 그래서 여러분들의 .pypirc 파일에 다음과 같이 값을 채워주면 됩니다.

[pypi]
  username = __token__
  password = pypi-AgE...[생략]...bHMWc

혹은 여러 계정을 관리해야 한다면?

[distutils]
index-servers=
    mypypi
    testpypi

[mypypi]
  username = __token__
  password = pypi-AgE...[생략]...bHMWc

[testpypi]
  username = __token__
  password = pypi-AgE...[생략]...bHMWc

(다중 설정의 경우 twine 명령행에 "--repository testpypi"와 같은 식으로 선택할 수 있습니다.)

이 정도면 기본적인 사용법은 대충 마무리된 것 같습니다. 이후에는 낯선 옵션과 용어들을 좀 더 넓혀가는 것만 남았군요. ^^




개인적으로, 처음 setup.py를 봤을 때 직관적으로 잘 이해할 수 없었습니다. 보통 그동안의 경험상 setup이라고 하면 설치 파일(setup.exe)을 연상하게 되는데 이번 경우에는 "make_package"에 해당하기 때문에 혼란이 온 것입니다. (어쨌든, "set up a package"라는 의미였겠지만... ^^;)

참고로, 아래의 글도 읽어보시길 권장합니다.

Deep Dive into pip - 1
; https://suhwan.dev/2018/10/24/deep-dive-into-pip-1/

Deep Dive into pip - 2
; https://suhwan.dev/2018/10/30/deep-dive-into-pip-2/

The Pip Python Package Manager
; https://www.datacamp.com/community/tutorials/pip-python-package-manager

그나저나, setup.py를 이용한 방식도 이젠 legacy라고... ^^;

setup.py 멈춰!
; https://tech.buzzvil.com/blog/setup.py-%EB%A9%88%EC%B6%B0/




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/7/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242107Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242479개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242309개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242056개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241896Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241828닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241826Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241876오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241922VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242051Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242146개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242214닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242268닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242374닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242206닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242039닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242241닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242149닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242029닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242010닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241895닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242033Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241959오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242048닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...