[9장] 공식 문서로 알아보는 Python 표준 라이브러리의 모든 것

박주원
July 26, 2025

[9장] 공식 문서로 알아보는 Python 표준 라이브러리의 모든 것

Use Original Cover Image
Type
Post
Children
Language
ko
Tags
Python
Library
OS
shutil
argparse
Regex
math
urllib
random
statistics
smtplib
datetime
doctest
unittest
Authors
박주원
Published
July 26, 2025

개요

본 글은 Python v3.13 공식 Tutorial의 10. Brief Tour of Standard Library 의 내용을 보다 이해하기 쉽게 정리한 글이다.
 

1. 운영 체제 인터페이스

1.1 os 모듈

import os print(os.getcwd()) os.chdir('/server/accesslogs') os.system('mkdir today')
page icon
C:\\path\\to\\folder\\repository
os 모듈은 운영 체제와 상호 작용할 수 있는 여러가지 함수를 제공한다.
 
모듈을 임포트할 때 from os import * 보다는 import os 형식으로 쓰도록 주의하자.
왜냐하면 Python의 빌트인 함수인 open()과, os 모듈의 함수 os.open() 이 서로 충돌하는 것을 방지하기 위해서이다.
 
import os print(dir(os)) print(help(os))
page icon
['DirEntry', 'EX_OK', 'F_OK', 'GenericAlias', ...] Help on module os: NAME os - OS routines for NT or Posix depending on what system we're on. ...
또한 모듈에 대한 자세한 정보를 얻기 위해 dir 함수나 help 함수를 사용할 수도 있다.
dir 은 모듈이 내보내는 모든 컨텐츠를 리스트로 반환하고, help 는 모듈의 docstring을 기반으로 모듈에 대한 메뉴얼을 만들어 낸다.
 

1.2 shutil 모듈

import shutil shutil.copyfile('data.db', 'archive.db') shutil.move('/build/executables', 'installdir')
shutil 모듈은 간편하게 파일과 폴더를 제어할 수 있는 함수들을 제공한다.
 

2. 파일 와일드 카드

import glob print(glob.glob('*.py'))
page icon
['code1.py', 'code2.py', 'tmp.py']
glob 모듈은 파일들을 와일드 카드로 찾을 수 있게 하는 함수를 제공한다.
 

3. 커맨드 실행 인자

3.1 sys.argv

# demo.py 파일 import sys print(sys.argv)
page icon
PS C:\path\to\folder> python demo.py 1 Hello True ['demo.py', '1', 'Hello', 'True']
sys 모듈은 Python파일을 실행할 때 argument로 받는 값들을 sys.argv 으로 받을 수 있게 한다.
 

3.2 argparse 모듈

# demo.py 파일 import argparse parser = argparse.ArgumentParser( prog='top', description='Show top lines from each file') parser.add_argument('filenames', nargs='+') parser.add_argument('-l', '--lines', type=int, default=10) args = parser.parse_args() print(args)
page icon
PS C:\path\to\folder> python demo.py usage: top [-h] [-l LINES] filenames [filenames ...] top: error: the following arguments are required: filenames
page icon
PS C:\path\to\folder> python demo.py file.txt -l 3 Namespace(filenames=['file.txt'], lines=3)
argparse 모듈은 Python파일의 실행 argument를 더 고급스럽게 받을 수 있게 한다.
 

4. 에러 메세지와 프로그램 종료

import sys sys.stderr.write('오류가 발생했습니다.') sys.exit(1)
page icon
오류가 발생했습니다.
sys 모듈은 또한 stderr 을 통해 에러 메세지를 작성할 수 있게 한다.
sys.exit 함수는 프로그램의 실행을 중지하는 함수이고, 특정 종료 코드를 할당할 수 있다.
종료 코드 1 은 비정상적인 종료를 의미한다.
 

5. Regex 매칭

import re print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')) print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')) print('tea for too'.replace('too', 'two'))
page icon
['foot', 'fell', 'fastest'] cat in the hat tea for two
re 모듈을 사용함으로써 정규식으로 문자열의 매칭, 검색, 치환 등을 수행할 수 있다.
 

6. 수학 관련

6.1 math 모듈

import math print(math.cos(math.pi / 4)) print(math.log(1024, 2))
page icon
0.7071067811865476 10.0
math 모듈은 수학에서의 기본적인 함수과 상수들을 지원한다.
지원하는 함수와 상수들은 C언어 표준을 따른다.
 

6.2 random 모듈

import random print(random.choice(['apple', 'pear', 'banana'])) print(random.sample(range(100), 10)) print(random.random()) print(random.randrange(6))
page icon
apple [14, 40, 78, 99, 21, 85, 18, 64, 54, 27] 0.9291587367817131 4
page icon
banana [81, 44, 9, 88, 87, 17, 90, 24, 29, 66] 0.5187855811434525 3
random 모듈은 무작위와 확률에 관련한 꽤 많은 것들을 지원한다.
C언어와 달리, 랜덤을 사용하기 위해 초기의 seed 초기화 등의 작업을 요구하지 않는다.
 

6.3 statistics 모듈

import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] print(statistics.mean(data)) print(statistics.median(data)) print(statistics.variance(data))
page icon
1.6071428571428572 1.25 1.3720238095238095
statistics 모듈은 통계학과 관한 많은 것들을 지원한다.
 

7. 인터넷 접근

7.1 urllib 패키지

from urllib.request import urlopen with urlopen('https://timeapi.io/api/time/current/zone?timeZone=Etc%2FUTC') as response: data = response.read() data = data.decode('utf-8') print(data)
page icon
{"year":2025,"month":7,"day":26,"hour":8,"minute":27,"seconds":47,"milliSeconds":397,"dateTime":"2025-07-26T08:27:47.3977202","date":"07/26/2025","time":"08:27","timeZone":"Etc/UTC","dayOfWeek":"Saturday","dstActive":false}
urllib 패키지는 URL과 관련한 여러 모듈들을 포함하고 있다.
urllib.request 모듈은 URL 요청, 주로 HTTP 요청을 할 수 있게 해준다.
 

7.2 smtplib 모듈

import smtplib server = smtplib.SMTP('localhost') server.sendmail('soothsayer@example.org', 'jcaesar@example.org', """To: jcaesar@example.org From: soothsayer@example.org Beware the Ides of March. """) server.quit()
smptlib 모듈은 SMPT 클라이언트를 생성하고 메일을 보낼 수 있게 해준다.
 

8. 시간과 날짜

from datetime import date now = date.today() print(now) print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")) birthday = date(1964, 7, 31) age = now - birthday print(age.days)
page icon
2025-07-24 07-24-25. 24 Jul 2025 is a Thursday on the 24 day of July. 22273
datetime 모듈은 날짜와 시간에 관련한 여러가지 기능들을 지원한다.
날짜와 시간 뿐만 아니라, 날짜의 출력 formatting이나 timezone또한 지원한다.
 

9. 데이터 압축

import zlib s = b'witch which has which witches wrist watch' print(len(s)) t = zlib.compress(s) print(len(t)) print(zlib.decompress(t)) print(zlib.crc32(s))
page icon
41 37 b'witch which has which witches wrist watch' 226805979
Python에서는 데이터를 압축하기 위해 zlib 모듈을 포함한, gzip , bz2 , lzma , zipfile , tarfile 등의 모듈을 지원한다.
 

10. 성능 측정

from timeit import Timer print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()) print(Timer('a,b = b,a', 'a=1; b=2').timeit())
page icon
0.017941600002814084 0.009880399997200584
Python에서 프로그램의 성능을 측정해야 할 때, timeit 같은 모듈을 사용할 수 있다.
timeit 모듈은 문자열로 작성된 코드를 실행하는데 걸리는 시간을 측정할 수 있게 해준다.
이보다 더 큰 코드 블록을 실행해야 할 경우에는 profile , pstats 등의 모듈을 사용할 수 있다.
 

11. 테스트

11.1 doctest 모듈

def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest print(doctest.testmod())
page icon
TestResults(failed=0, attempted=1)
doctest 모듈은 프로그램의 docstring을 기반으로 간편하게 테스트를 실행하고 결과를 볼 수 있게 해준다.
 

11.2 unittest

import unittest def average(values): return sum(values) / len(values) class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main()
page icon
. ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
unittest 모듈은 유닛 테스트를 진행할 수 있도록 하는 도구들을 제공한다.
 

12. “Batteries Included” 철학

Python은 “Batteries Included” 철학을 Python 표준 모듈의 모토로 내세운다.
“Batteries Included” 라는 것은 별도의 추가 모듈을 받지 않고도 표준 모듈만으로 대부분의 작업을 수행할 수 있다는 것이다.
본 문서에서도 다양한 표준 모듈들을 짧게 살펴 보았지만, 이외에도 Python에서는 200 개가 넘는 표준 모듈들을 지원하고 있다.
이처럼 Python은 대다수의 기능들을 빌트인 모듈로 지원함으로써 외부 패키지의 사용을 최소화 시킨다는 “Batteries Included” 철학을 따른다.
 

Reference

[1] Python Software Foundation. "10. Brief Tour of the Standard LibraryThe Python Tutorial, version 3.13, Python Software Foundation, 2024, https://docs.python.org/3.13/tutorial/stdlib Accessed 26 July 2025.