처음 프로그램을 공부하며 파이썬을 접하는 입장에서 모듈을 임포트 하고 실행하는 것은 진입장벽이 있는 어려운 일이었다. 하지만 직접 모듈을 만들어보고 임포트 해보면 다른 사람이 정의해 놓은 함수를 사용하기 위한 과정으로 어느 정도 이해가 된다.
1. 먼저 함수를 정의하고 *.py파일로 저장한다.
def NewModule():
print("Hello World")
2. 모듈을 만들기 위해서 setup.py파일을 작성한다.
from distutils.core import setup
setup(
name= 'NewModule',
version= '1.0',
py_modules = ['NewModule'],
author = 'abankclerk',
author_email= 'abankclerk@abankclerk.com',
url = 'http://abankclerk.tistory.com',
description= 'An example of making a module'
)
3. 윈도우 명령어 창에서 배포패키지를 만들고 명령어를 입력한다. 여기까지 진행하면 배포패키지는 완성이다. 우리가 임포트 하는 모듈은 위와 같은 과정을 통해서 만들어진다.
C:\Users\KwonT\PycharmProjects\modules_190411>python setup.py sdist
==== 아래와 같은 메시지와 함께 배포 패키지가 완성된다. ====
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)
warning: sdist: standard file not found: should have one of README, README.txt, README.rst
writing manifest file 'MANIFEST'
creating NewModule-1.0
making hard links in NewModule-1.0...
hard linking NewModule.py -> NewModule-1.0
hard linking setup.py -> NewModule-1.0
creating dist
Creating tar archive
removing 'NewModule-1.0' (and everything under it)
4. 이제부터는 사용자의 입장으로 만들어진 배포 패키지를 설치한다.
(venv) C:\Users\KwonT\PycharmProjects\modules_190411>python setup.py install
=== 아래와 같은 메시지가 나오면서 설치된다. ===
running install
running build
running build_py
creating build
creating build\lib
copying NewModule.py -> build\lib
running install_lib
copying build\lib\NewModule.py -> C:\Users\KwonT\PycharmProjects\modules_190411\venv\Lib\site-packages
byte-compiling C:\Users\KwonT\PycharmProjects\modules_190411\venv\Lib\site-packages\NewModule.py to NewModule.cpython-37.pyc
running install_egg_info
Writing C:\Users\KwonT\PycharmProjects\modules_190411\venv\Lib\site-packages\NewModule-1.0-py3.7.egg-info
5. 콘솔창에서 import 모듈명으로 모듈을 임포트 한다.
>>>import NewModule
6. 다른 모듈의 네임스페이스에 연결되어 있으므로 모듈명.함수명으로 함수를 실행시킨다.
>>>NewModule()
Traceback (most recent call last):
File "", line 1, in
TypeError: 'module' object is not callable
>>>NewModule.NewModule()
Hello World
'Python일기' 카테고리의 다른 글
파이썬 모듈 임포트(feat. pycharm) (0) | 2019.08.10 |
---|---|
파일에서 읽고 쓰기 (0) | 2019.05.03 |
if 조건문 만들기 (0) | 2019.04.12 |
루프만들기(for, while문) (0) | 2019.04.12 |
리스트 만들기 (0) | 2019.04.11 |