[파이썬3.0] 모듈 공유

프로그램 언어/파이썬|2014. 6. 15. 13:27

모듈 공유

 

자 방금 전까지는 한 줄에 모든 내용을 저장했다.

그렇기에 사용자가 데이터를 보기에는 좋지 않은 형태였는데

이번에는 한 줄씩 끊어서 저장함으로써 사용자가 데이터를 확인하는데

좀 더 편리하게 해보자.

 

Write.py

import nest

man = []

other = []

 

try:

    data = open('sketch.txt')

 

    for each_line in data:

        try:

            (role, line_spoken) = each_line.split(':')

            line_spoken = line_spoken.strip()

            if role == 'Man':

                man.append(line_spoken)

            elif role == 'Other Man':

                other.append(line_spoken)

            else:

                pass

        except ValueError:

            pass

 

    data.close()

except IOError:

    print('The datafile is missing!')

 

try:

    with open('man.txt', 'w') as man_file, open('other.txt', 'w') as other_file:

nest.print_lol(man, fh=man_file)

#file이 아니라 fh로 한 이유는 함수 인자 때문.

        nest.print_lol(other, fh=other_file)

except IOError as err:

    print('File error: ' + str(err))

write.py에서 크게 바뀐 내용은 없다.

하지만 with절에 있는 print들이 nest.print_lol로 바뀌었다. Nest모듈을 임포트해서 nest모듈 안에 있는 함수를 사용하겠다는 것이다.

 

Nest.py

import sys

 

def print_lol(the_list, indent=False, level=0, fh=sys.stdout):

""" Prints a list of (possibly) nested lists.

     이것은 라인 바이 라인 형태로 출력하기 위한 함수

""" 

for each_item in the_list:

    if isinstance(each_item, list):

        print_lol(each_item, indent, level+1, fh)

    else:

        if indent:

            for tab_stop in range(level):

                print("\t", end='', file=fh)

        print(each_item, file=fh)

 

이 모듈 안에 있는 함수가 한 줄씩 나눠서 저장하게 해주는 형태의 함수이다.

 

그럼 여기서 모듈을 어떻게 임포트하는 것일까?

우리가 만든 하나의 파일을 모듈이라고 한다.

그럼 그냥 불러와서 쓰면 되나?

설치 작업이 필요하다.

패키지를 만들고 모듈을 설치를 하면 되는데 방법은 아래와 같다.

 

Setup.py

from distutils.core import setup

 

setup(

    name = 'ex_nest',

    version = '1.0.0',

   ## TODO: be sure to change these next few lines to match your details!

    py_modules = ['nest'],

    author = 'pythoner',

    author_email = 'kshyun87.tistory.com',

    url = 'kshyun87.tistory.com',

    description = 'A simple printer of nested lists',

)

Setup파일을 만들어서 setup을 임포트 시켰다.

패키지를 생성시키기 위해서는 그 setup에 필요한 인자들을 넣어주고 패키지를 만들면 된다.

 

아래 그림이 패키지 생성과 설치를 보여준다.

패키지를 만들 폴더의 경로로 가서 setup.py를 실행시키되 sdist를 붙여서 실행 하면 된다.

설치를 할 때는 install을 사용하면 된다.

애플이나 리눅스와 같은 형태라면 sudo명령어가 필요하고, 패키지 생성시 python3과 같은 형태를 파이썬 실행 경로대신에 사용 가능하다.

 

 

모듈을 import하기 위해서

배포패키지를 만들고 만든 것을 설치하여 모듈을 사용자 os에 설치해야 한다.

참고 : head first python

댓글()