Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 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 패키지 만들기 (3) entry_points 옵션

지난 글에 다룬,

파이썬 - PyPI 패키지 만들기
; https://www.sysnet.pe.kr/2/0/12863

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

setup.py의 옵션 중에는 entry_points라는 것이 있습니다.

setup(
    name="net-util",
    description="utility functions for networking",
    long_description=readme(),
    long_description_content_type='text/markdown',
    # cmdclass={'sdist': UserCode},
    cmdclass={'bdist_wheel': UserCode},
    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"],

    entry_points={
        'console_scripts': [
            'netutil-admin = netutil.admin:main',
        ],
    },
)

위와 같이 지정한 경우라면, 당연히 "netutil.admin" 패키지가 있어야 합니다. 예를 들어 간단하게 다음과 같은 식의 파일을 만들 수 있습니다.

# ./netutil/admin/__init__.py


def main():
    print('net-util administrations')

그럼, "pip install ..." 시에 위의 "netutil.admin::main"을 호출하는 'netutil-admin.py'를 사용자 디렉터리($HOME/.local/bin)에 다음과 같은 식으로 pip 프로그램이 생성해 줍니다.

/home/testusr/.local/bin$ cat netutil-admin
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from netutil.admin import main
if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

따라서 일종의 프로그램을 하나 제공하는 효과를 얻게 되는데 실제로 해당 명령어를 실행하는 것도 가능합니다.

$ netutil-admin
net-util administrations

이렇게 만드는 경우 주의할 것이 있다면 바로, 해당 파일(위의 경우 __init__.py)에서 같은 프로젝트에 포함된 모듈을 import하는 경우 명시적으로 상대 경로를 지정해야 하는 상황도 있다는 점입니다.

예를 들어, __init__py와 동일한 디렉터리에 info.py가 있고,

# ./netutil/admin/info.py


def help_cmd():
    print('netutil-admin')
    pass

위의 기능을 이용하기 위해 단순히 __init__.py에서는 다음과 같이 사용할 수 있습니다.

# ./netutil/admin/__init__.py

import info


def main():
    print('net-util administrations')
    info.help_cmd()

하지만, 이것이 entry_points로 등록된 경우라면 상황이 달라집니다.

entry_points={
    'console_scripts': [
        'netutil-admin = netutil.admin:main',
    ],
},

저런 경우에는 netutil.admin 패키지에서 site-packages 경로를 기준으로 "import info"를 찾기 때문에 "ModuleNotFoundError: No module named 'info'"라는 예외가 발생합니다.

따라서, 상대 경로로 import를 해야 하는데 import 구문에는 상대 경로를 지정할 수 없으므로 sys.path.append를 이용하거나 다음과 같이 from 구문으로 바꿔 상대 경로를 지정하면 됩니다.

# ./netutil/admin/__init__.py

from .info import help_cmd


def main():
    print('net-util administrations')
    help_cmd()




entry_points로 등록한 경우 리눅스에서는 shell script로 "$HOME/.local/bin" 경로에 파일이 생성되는데, 그렇다면 윈도우의 경우에는 어떨까요?

개인적인 예상으로는 사실 지원하지 않을 거라고 생각했습니다. 왜냐하면, 윈도우의 경우 "%USERPROFILE%" 경로가 기본적으로 PATH 환경 변수에 등록되어 있진 않으므로 단순히 jennifer-admin.cmd 파일을 생성한다고 해서 실행되지는 않을 것이므로 여러모로 불편할 수 있습니다.

하지만, 지원을 합니다. ^^ 경로는, Python 설치 경로의 ".\Scripts\" 하위 디렉터리에 무려 EXE 파일로 생성이 됩니다. (cmd/bat가 아닌 굳이 왜 EXE로 했는지는 알 수 없지만!)

재미있는 것은, 윈도우 버전의 파이썬 Script 디렉터리에 있는 exe 파일들이,

pypi_adv_2.png

하나같이 104KB 크기로 된 것으로 봐서는 거의 템플릿화 되어 있는 듯합니다. 게다가 pip.exe 등도 결국 사용자가 컴파일해서 제공하는 것이 아닌, 결국 파이썬 모듈을 호출하는 console_scripts 설정으로 만들어진 실행 모듈이었던 것입니다. 그렇다면, 리눅스에서는 당연히 shell script로 연결된 것이라는 것을 유추할 수 있습니다. ^^

$ cat /usr/bin/pip
#!/usr/bin/python3
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==20.0.2','console_scripts','pip'
__requires__ = 'pip==20.0.2'
import re
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(
        load_entry_point('pip==20.0.2', 'console_scripts', 'pip')()
    )




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







[최초 등록일: ]
[최종 수정일: 12/8/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)
13854정성태12/27/20245865C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244809디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20245900디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20245097디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20246221오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20246190디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20245686디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20245758오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20246316디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20245163디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20246676디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20245192오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20245380디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20246017오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20245267오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20246232오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20245956오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20246746디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20245296디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20246728오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20246704Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20246079개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20245717Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20245067Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20246570개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20246693스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...