[Python] 모듈과 패키지 관리
Y
Yerim
- Python
# mod1.py
def add(a, b):
return a + b
def sub(a, b):
return a-bC:\Users\pahkey>cd C:\doit
C:\doit>dir
C:\doit>pythonimport mod1
print(mod1.add(3, 4))
print(mod1.add(4, 2))import 모듈_이름 # 전체 모듈을 import 하는 경우
from 모듈_이름 import 모듈_함수 # 모듈 이름 없이 함수의 이름만 사용하고 싶은 경우
from 모듈_이름 import * # 모듈의 전체 함수를 import# mod1.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
print(add(1, 4)) # 5
print(sub(4, 2)) # 2# mod1.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
if __name__ == "__main__":
print(add(1, 4)) # 5
print(sub(4, 2)) # 2# mod2.py
PI = 3.141592
class Math:
def solv(self, r):
return PI * (r ** 2)
def add(a, b):
return a+b import mod2
print(mod2.PI) # mod2.py파일에 있는 PI 변수의 값을 사용할 수 있다
a = mod2.Math()
print(a.solv(2)) # 12.566368
print(mod2.add(mod2.PI, 4.4)) # 7.541592# modtest.py
import mod2
result = mod2.add(3, 4)
print(result)# sys.path.append 사용하기
import sys
sys.path.append("C:/doit/mymod")
# PYTHONPATH 환경 변수 사용하기
set PYTHONPATH=C:\doit\mymodpip listimport pandas as pd
import my_module
from my_module import a, b, c
from a.b.my_module import hello# sampletest.py
name = 'hojun'import sampletest
sampltest.namegame/
__init__.py
sound/
__init__.py
echo.py
wav.py
graphic/
__init__.py
screen.py
render.py
play/
__init__.py
run.py
test.pyC:/doit/game/__init__.py
C:/doit/game/sound/__init__.py
C:/doit/game/sound/echo.py
C:/doit/game/graphic/__init__.py
C:/doit/game/graphic/render.py# echo.py
def echo_test():
print("echo")# render.py
def render_test():
print("render")# 방법 1 - echo 모듈은 echo.py 파일
import game.sound.echo
game.sound.echo.echo_test()
# 방법 2 - echo 모듈에 있는 디렉토리까지 from … import 하여 실행하는 방법
from game.sound import echo
echo.echo_test()
# 방법 3 - echo 모듈의 echo_test 함수를 직접 import
from game.sound.echo import echo_test
echo_test()# C:/doit/game/__init__.py
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")# C:/doit/game/__init__.py
from .graphic.render import render_test
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")# C:/doit/game/__init__.py
from .graphic.render import render_test
VERSION = 3.5
def print_version_info():
print(f"The version of this game is {VERSION}.")
# 여기에 패키지 초기화 코드를 작성한다.
print("Initializing game ...")__all__ = ['echo']