Topic 3: 외부 패키지 사용하기 🌐
🎯 학습 목표
외부 패키지를 설치하고 사용하는 방법을 배워요!
- pip가 무엇인지 이해하기
- 패키지 설치와 삭제하기
- 인기 있는 패키지 사용해보기
📦 pip란?
pip는 Python Package Installer의 약자로, 파이썬 패키지를 쉽게 설치할 수 있게 해주는 도구예요. 마치 앱스토어에서 앱을 다운로드하는 것과 같아요!
pip 확인하기
# 터미널/명령 프롬프트에서 실행
pip --version
# 또는
pip3 --version
📥 패키지 설치하기
기본 설치 명령어
# 패키지 설치
pip install 패키지이름
# 예시: requests 패키지 설치
pip install requests
# 특정 버전 설치
pip install requests==2.28.0
# 최신 버전으로 업그레이드
pip install --upgrade requests
설치된 패키지 확인
# 설치된 모든 패키지 보기
pip list
# 특정 패키지 정보 보기
pip show requests
패키지 삭제
# 패키지 삭제
pip uninstall requests
🌟 인기 패키지 체험하기
1. requests - 웹 페이지 가져오기
# 설치
pip install requests
import requests
# 웹 페이지 내용 가져오기
response = requests.get("https://api.github.com")
# 상태 코드 확인
print(f"상태 코드: {response.status_code}")
# JSON 데이터 파싱
if response.status_code == 200:
data = response.json()
print(f"GitHub API 버전: {data['current_user_url']}")
2. colorama - 컬러풀한 출력
# 설치
pip install colorama
from colorama import init, Fore, Back, Style
# colorama 초기화
init()
# 색상 있는 텍스트 출력
print(Fore.RED + "빨간색 텍스트")
print(Fore.GREEN + "초록색 텍스트")
print(Back.YELLOW + "노란 배경" + Style.RESET_ALL)
# 게임 메시지 예시
print(Fore.CYAN + "🎮 게임을 시작합니다!")
print(Fore.GREEN + "✅ 정답입니다!")
print(Fore.RED + "❌ 틀렸습니다!")
print(Style.RESET_ALL + "일반 텍스트")
3. tqdm - 진행 상황 표시
# 설치
pip install tqdm
from tqdm import tqdm
import time
# 진행 막대 표시
print("파일 다운로드 중...")
for i in tqdm(range(100), desc="진행률"):
time.sleep(0.01) # 실제로는 작업 수행
# 리스트 처리 시 진행 상황
items = ["파일1", "파일2", "파일3", "파일4", "파일5"]
for item in tqdm(items, desc="처리 중"):
time.sleep(0.5) # 파일 처리 시뮬레이션
# 실제 작업 수행
💪 실용적인 예제
날씨 정보 가져오기
import requests
def get_weather(city="Seoul"):
"""날씨 정보를 가져오는 함수"""
# OpenWeatherMap API (무료 API 키 필요)
api_key = "YOUR_API_KEY" # 실제 사용 시 API 키 필요
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
temp = data['main']['temp']
desc = data['weather'][0]['description']
print(f"{city}의 날씨:")
print(f"온도: {temp}°C")
print(f"상태: {desc}")
else:
print("날씨 정보를 가져올 수 없습니다.")
except Exception as e:
print(f"에러 발생: {e}")
# 사용 예시 (API 키가 있을 때)
# get_weather("Seoul")
텍스트 게임 만들기
from colorama import init, Fore, Style
from tqdm import tqdm
import time
import random
# colorama 초기화
init()
def adventure_game():
"""간단한 텍스트 어드벤처 게임"""
print(Fore.CYAN + "🏰 모험을 시작합니다!" + Style.RESET_ALL)
# 로딩 시뮬레이션
print("\n게임 로딩 중...")
for _ in tqdm(range(50)):
time.sleep(0.02)
print(Fore.GREEN + "\n숲 속에서 깨어났습니다..." + Style.RESET_ALL)
while True:
print("\n무엇을 하시겠습니까?")
print("1. 북쪽으로 가기")
print("2. 남쪽으로 가기")
print("3. 주변 살펴보기")
print("4. 게임 종료")
choice = input(Fore.YELLOW + "선택 (1-4): " + Style.RESET_ALL)
if choice == "1":
print(Fore.BLUE + "북쪽으로 갔더니 아름다운 호수가 있습니다! 🏞️" + Style.RESET_ALL)
elif choice == "2":
print(Fore.RED + "남쪽으로 갔더니 무서운 동굴이 있습니다! 🦇" + Style.RESET_ALL)
elif choice == "3":
items = ["🗝️ 열쇠", "🍎 사과", "⚔️ 검", "💎 보석"]
found = random.choice(items)
print(Fore.GREEN + f"주변을 살펴보니 {found}를 발견했습니다!" + Style.RESET_ALL)
elif choice == "4":
print(Fore.CYAN + "게임을 종료합니다. 안녕! 👋" + Style.RESET_ALL)
break
else:
print(Fore.RED + "잘못된 선택입니다!" + Style.RESET_ALL)
# 게임 실행
adventure_game()
📋 requirements.txt 사용하기
프로젝트에서 사용하는 패키지들을 관리하는 방법이에요.
requirements.txt 만들기
# 현재 설치된 패키지 목록 저장
pip freeze > requirements.txt
requirements.txt로 설치하기
# 파일에 있는 모든 패키지 설치
pip install -r requirements.txt
requirements.txt 예시:
requests==2.28.0
colorama==0.4.6
tqdm==4.65.0
💡 퀴즈: pip 이해도 체크
Q1. 패키지를 최신 버전으로 업그레이드하는 명령어는?
💡 정답 확인
정답: pip install --upgrade 패키지이름
예시:
pip install --upgrade requests
Q2. 설치된 모든 패키지를 보는 명령어는?
pip show
pip list
pip freeze
- 2번과 3번 모두
💡 정답 확인
정답: 4번
pip list
: 보기 쉬운 형태로 출력pip freeze
: requirements.txt 형식으로 출력- 둘 다 설치된 패키지를 보여줘요!
✅ 외부 패키지 사용 마스터 체크리스트
✅ 외부 패키지 사용 마스터 체크리스트
🚀 다음 단계
외부 패키지 사용법을 익혔나요? 마지막으로 우리가 직접 모듈을 만들어서 재사용하는 방법을 배워볼게요!
Last updated on