동적 모듈 로딩
문자열로 표현된 모듈 이름을 동적으로 불러오는 방법은 다음과 같습니다:
import importlib
# __import__ 함수 사용 (권장하지 않음)
module = __import__('math')
# importlib.import_module를 통한 안전한 동적 로딩
module = importlib.import_module('collections.abc')
print(module) # <module 'collections.abc' from '...>
모듈 임포트의 동작 원리
모듈을 임포트할 때는 해당 파일이 실행되며, 전역 변수와 함수가 메모리에 로드됩니다.
# cal.py
print("모듈 로드 시작")
def add(a, b):
return a + b
print("모듈 로드 완료")
# test.py
from cal import add # 위의 출력 문장들이 먼저 실행됨
result = add(3, 4)
주의: from web.web1 import web2 형식의 다단계 임포트는 동작하지 않을 수 있으며, 이는 패키지 구조나 상대 경로 설정에 따라 달라집니다.
또한, if __name__ == "__main__": 블록은 모듈 자체를 실행했을 때만 동작하며, 테스트용 코드를 포함하거나 다른 파일에서 임포트 시 무시됩니다.
시간 처리: time과 datetime 모듈
import time
import datetime
# 현재 시간 타임스탬프 (1970-01-01 기준 초수)
timestamp = time.time()
# 현지 시간 구조화
local_time = time.localtime()
print(local_time.tm_wday) # 요일 (0=월요일)
# 구조화된 시간 → 타임스탬프
ts = time.mktime(local_time)
# 구조화된 시간 → 포맷된 문자열
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
# 문자열 → 구조화된 시간
parsed = time.strptime("2024-05-30 10:20:30", "%Y-%m-%d %H:%M:%S")
# 구조화된 시간 → 문자열 (간단 버전)
asctime = time.asctime()
# 타임스탬프 → 문자열
ctime_str = time.ctime(timestamp)
# datetime 모듈 사용 예
now = datetime.datetime.now()
print(now) # 2024-05-30 10:25:30.123456
난수 생성: random 모듈
import random
# 0.0 ~ 1.0 사이 난수
random.random()
# 정수 범위 내 난수
random.randint(1, 10) # [1, 10] 포함
random.randrange(1, 10) # [1, 10) 미포함
# 리스트에서 하나 선택
random.choice(['A', 'B', 'C'])
# 중복 없이 여러 개 선택
random.sample([1, 2, 3, 4], 2) # 예: [3, 1]
# 실수 범위 내 난수
random.uniform(1.0, 3.0)
# 리스트 순서 무작위 섞기
data = [10, 20, 30, 40]
random.shuffle(data) # [40, 10, 30, 20]
# 5자리 랜덤 코드 생성 함수
def generate_code():
result = ""
for _ in range(5):
choice = random.choice([
str(random.randint(0, 9)),
chr(random.randint(65, 90)), # 대문자
chr(random.randint(97, 122)) # 소문자
])
result += choice
return result
print(generate_code()) # 예: K8xQ2
시스템 및 운영체제 관련: sys, os 모듈
import sys
import os
# 경로 추가 (임시)
sys.path.append('/path/to/module')
# 플랫폼 정보 확인
platform = sys.platform
# 명령행 인자
args = sys.argv
# 표준 출력 직접 제어
sys.stdout.write('#')
sys.stdout.flush() # 즉시 출력 강제
# 진행률 바 예제
for i in range(100):
sys.stdout.write('#')
sys.stdout.flush()
time.sleep(0.05)
# 디렉토리 작업
current_dir = os.getcwd()
os.chdir('subdir') # 하위 폴더 이동
# 시스템 명령어 실행
os.system('ls -l')
# 경로 조작
directory, filename = os.path.split('/path/to/file.txt')
joined_path = os.path.join('folder', 'sub', 'file.py')
# 파일 정보 조회
file_info = os.stat('example.py')
last_modified = os.path.getmtime('example.py')
정규표현식: re 모듈
import re
# 일치하는 패턴 찾기 (첫 번째 매칭)
match = re.search(r'\d+', 'abc123xyz')
if match:
print(match.group()) # '123'
# 그룹 이름 지정
result = re.search(r'(?P<name>[a-z]+)(?P<age>\d+)', 'alice25bob30')
print(result.group('name', 'age')) # ('alice', '25')
# 시작부분부터 일치 여부 확인
start_match = re.match(r'^\d+', '123abc')
if start_match:
print(start_match.group())
# 문자열 분할
parts = re.split(r'[| ]', 'hello|world test') # ['hello', 'world', 'test']
# 패턴으로 치환
replaced = re.sub(r'\d+', 'X', 'abc123def456') # 'abcXdefX'
# 컴파일된 패턴 재사용
pattern = re.compile(r'\d{3,5}')
matches = pattern.findall('123 4567 89')
# 반복 검색 객체
iter_matches = re.finditer(r'\d+', '123abc456')
for m in iter_matches:
print(m.group())
# 그룹 비저장 (비캡처 그룹)
result = re.findall(r'www\.(?:google|baidu)\.com', 'www.google.com') # ['www.google.com']
로그 기록: logging 모듈
import logging
# 기본 설정
logging.basicConfig(
level=logging.DEBUG,
filename='app.log',
filemode='w',
format='%(asctime)s | %(filename)s | Line %(lineno)d | %(message)s'
)
logging.debug('디버그 메시지')
logging.info('정보 메시지')
logging.warning('경고 메시지')
logging.error('오류 메시지')
logging.critical('심각 오류 메시지')
# 커스텀 로거 설정
logger = logging.getLogger('my_app')
handler_file = logging.FileHandler('debug.log')
handler_stream = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler_file.setFormatter(formatter)
handler_stream.setFormatter(formatter)
logger.addHandler(handler_file)
logger.addHandler(handler_stream)
logger.setLevel(logging.DEBUG)
# 사용 예
logger.debug('응용 로그 메시지')
해시 암호화: hashlib 모듈
import hashlib
# MD5 해시 생성
hash_obj = hashlib.md5()
hash_obj.update('hello'.encode('utf-8'))
print(hash_obj.hexdigest()) # 5d41402abc4b2a76b9719d911017c592
# SHA-256 사용 예시
sha256_obj = hashlib.sha256()
sha256_obj.update(b'secret data')
print(sha256_obj.hexdigest())