Python은 대부분의 Library가 이미 다른 사용자에 의해서 구현되어 있다.
# module_ex.py
import fah_converter
print("Enter a celsius value: ")
celsius = float(input())
fahrenheit = fah_converter.convert_c_to_f(celsius)
print("That's", fahrenheit, "degrees Fahrenheit")
Enter a celsius value: 10
That's 50.0 degrees Fahrenheit
- Namespace Example
1) Module명을 별칭으로 사용해서 Alias 설정import fah_converter as fah # fah_converter를 fah라는 이름으로 print(fah.convert_c_to_f(41.6)) # 그 안에 convert_c_to_f 함수를 사용
2) Module에서 특정 Function 또는 Class만 호출
from fah_converter import convert_c_to_f print(convert_c_to_f(41.6)) # convert_c_to_f 함수만 호출
3) Module에서 모든 Function 또는 Class를 호출
from fah_converter import * print(convert_c_to_f(41.6)) # 전체 호출
# 난수
import random
print (random.randint(0, 100)) # 0 ~ 100 사이의 정수 난수를 생성
print(random.random()) # 일반적인 난수 생성
# 시간
import time
print(time.localtime()) # 현재 시간 출력
# 웹
import urllib.request
response = urllib.request.urlopen("https://www.youtube.com/watch?v=PXEu_OZKFBQ&list=LL&index=3")
print(response.read())
기능들을 세부적으로 나눠 폴더로 만든다
각 폴더별로 필요한 Module을 구현
# echo.py
def echo_play(echo_number):
print("echo {} number start".format(echo_number))
import echo
echo.echo_play(10)
# echo 10 number start
__all__ = ['image', 'stage', 'sound']
from . import image
from . import stage
from . import sound
from stage.main import game_start
from stage.sub import set_stage_level
from image.character import show_character
from sound.bgm import bgm_play
if __name__ == '__main__':
game_start()
set_stage_level(5)
bgm_play(10)
show_character()
from game.graphic.render import render_test # import : 절대참조
from .render import render_test # .render : 현재 디렉토리 기준
from ..sound.echo import echo_test # ..sound.echo : 부모 디렉토리 기준
대표적인 도구 Virtualenv와 Conda가 있음
Conda Virtual Environment
conda create -n my_project python=3.8
- conda create : Virtual Environment 새로 만들기
- -n my_project : Virtual Environment 이름
- python=3.8 : Python Version
Virtual Environment 호출과 해제
conda activate my_project conda deactivate
Package Install
# conda install <Package Name> conda install matplotlib
Windows > conda
Linux, Mac > pip
Conda Virtual Environment Example : Matplotlib을 활용한 Graph Visualize
- 대표적인 Python Graph Management Package
- Excell과 같은 Graph들을 화면에 표시
- 다양한 Data 분석 도구들과 함께 사용 ex) conda install tqdm
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show()
from tqdm import tqdm
import time
for i in tqdm(range(100000)):
if i % 1000 == 0:
time.sleep(1)