Python 내장 모듈 활용 가이드

내장 모듈의 종류와 사용법

time 및 datetime 모듈을 이용한 시간 처리

Python은 날짜와 시간을 다루기 위한 표준 라이브러리로 timedatetime을 제공한다. 이들은 타임스탬프, 구조화된 시간 튜플, 서식 문자열 등 다양한 형식 간 변환을 지원한다.

import time
import datetime

# 현재 시각의 타임스탬프 출력
print(time.time())

# 로컬 시간 (튜플 형태)
local_time = time.localtime()
print(local_time)

# 2초간 일시 정지
time.sleep(2)

# UTC 기준 시간 정보
utc_time = time.gmtime()
print(utc_time)

# 튜플 형식의 시간을 다시 타임스탬프로 변환
timestamp_from_tuple = time.mktime(local_time)
print(timestamp_from_tuple)

# 포맷팅된 문자열로 변환
formatted_str = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted_str)

# 문자열을 시간 튜플로 파싱
parsed_time = time.strptime("2019-11-08 01:52:03", "%Y-%m-%d %H:%M:%S")
print(parsed_time)

# 현재 날짜 및 시간 (datetime 객체)
now = datetime.datetime.now()
print(now)

# 3일 후, 3일 전 계산
print(now + datetime.timedelta(days=3))
print(now + datetime.timedelta(days=-3))

# 시간 단위 조정
print(now + datetime.timedelta(hours=8))
print(now + datetime.timedelta(hours=-8))

random 모듈: 난수 생성과 응용

random은 난수를 생성하는 데 사용되며, 보안이 요구되지 않는 일반적인 난수 필요 상황에 적합하다.

import random

# 0.0 ~ 1.0 사이 실수
print(random.random())

# 지정 범위 내 정수 추출
print(random.randint(1, 3))      # 1~3 포함
print(random.randrange(1, 3))   # 1~2

# 시퀀스에서 임의 요소 선택
print(random.choice('hello'))
print(random.sample('hello', 2))  # 두 개 무작위 선택

# 리스트 섞기
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
random.shuffle(items)
print(items)

예제: 인증 코드 생성

4자리 인증 번호를 숫자와 대문자 알파벳이 혼합된 형태로 생성할 수 있다.

verification_code = ''
for _ in range(4):
    if random.randint(0, 1):  # 확률 기반 선택
        verification_code += str(random.randint(0, 9))
    else:
        verification_code += chr(random.randint(65, 90))  # A~Z
print(verification_code)

os 모듈: 운영체제 인터페이스

os는 파일 시스템 작업, 환경 변수 접근, 디렉터리 관리 등을 가능하게 한다.

import os

# 현재 작업 디렉터리 확인
print(os.getcwd())

# 디렉터리 생성 및 삭제
os.makedirs('temp_dir/sub_dir', exist_ok=True)
os.removedirs('temp_dir/sub_dir')  # 재귀적 삭제

# 경로 관련 유틸리티
print(os.path.abspath('test.txt'))
print(os.path.dirname('/home/user/test.py'))
print(os.path.basename('/home/user/test.py'))

# 파일 존재 여부 및 속성 확인
print(os.path.exists('/tmp'))
print(os.path.isfile('test.txt'))
print(os.path.isdir('/home'))

# 플랫폼 정보
print(os.name)           # 예: 'posix', 'nt'
print(os.sep)            # 경로 구분자 ('/' 또는 '\')
print(os.linesep)        # 줄바꿈 문자

sys 모듈: 파이썬 인터프리터 제어

sys는 파이썬 실행 환경과 상호작용할 수 있게 해주는 모듈이다.

import sys

# 명령줄 인수 접근
if len(sys.argv) > 1:
    script_name = sys.argv[0]
    first_arg = sys.argv[1]
    print(f"스크립트: {script_name}, 인수: {first_arg}")

# 경로 추가 (모듈 임포트 경로 확장)
sys.path.append("/사용자/모듈")

# 표준 출력 리디렉션 예제
original_stdout = sys.stdout
with open("로그.txt", "w") as log_file:
    sys.stdout = log_file
    print("이 메시지는 파일에 저장됩니다.")
sys.stdout = original_stdout
print("콘솔로 출력 재개.")

프로그램 종료 제어

sys.exit()은 프로그램을 즉시 종료하며, SystemExit 예외를 발생시킨다.

while True:
    user_input = input("종료하려면 'exit' 입력: ")
    if user_input.lower() == 'exit':
        sys.exit("사용자 요청으로 종료합니다.")

shutil 모듈: 고수준 파일 조작

shutil은 파일 복사, 이동, 디렉터리 전체 삭제 및 압축 등의 고급 파일 작업을 지원한다.

import shutil
import os

# 파일 콘텐츠와 권한 복사
shutil.copy('source.txt', 'dest.txt')

# 디렉터리 전체 복사 (특정 확장자 제외)
shutil.copytree('src_folder', 'backup', ignore=shutil.ignore_patterns('*.log', '*.tmp'))

# 디렉터리 삭제
shutil.rmtree('unwanted_folder')

# 파일 이동 또는 이름 변경
shutil.move('old_name', 'new_name')

# 압축 파일 생성 (tar 형식)
shutil.make_archive('backup_data', 'gztar', root_dir='data_to_compress')

shelve 모듈: 데이터 영속성 저장

shelve는 딕셔너리처럼 작동하며, Python 객체를 파일에 저장하고 불러올 수 있다. 내부적으로 pickle을 사용한다.

import shelve
import time

# 데이터 저장
db = shelve.open('mydata')
db['user'] = 'anliu'
db['skills'] = ['Linux', 'Automation']
db['last_login'] = time.localtime()
db.close()

# 데이터 읽기
db = shelve.open('mydata')
print(db.get('skills'))
print(db.get('user'))
db.close()

태그: python time datetime Random os

7월 28일 01:20에 게시됨