표준 라이브러리(Standard Library) (1)
프로그래밍 언어의 기본 기능과 기능을 확장하는 데 사용할 수 있는 기본적인 모듈과 함수의 집합
Library : 원하는 정보(프로그램)를 찾아 사용하자
프로그래머가 기본적인 작업을 수행하기 위해 처음부터 모든 것을 작성하지 않고, 이미 구현된 함수와 모듈을 사용하여 빠르고 효율적으로 프로그램을 작성할 수 있도록 도와준다.
sys 모듈
파이썬 인터프리터가 제공하는 변수와 함수를 직접 제어할 수 있게 해주는 모듈
sys.argv
# Terminal, cmd, prompt에서
python test.py abc pey guido
--> 파일이름 뒤에 있는 값들이 sys.argv 리스트에 추가됨
sys.exit()
강제로 스크립트 종료하기
ctrl z 나 ctrl d 와 같은 기능
sys.path
# path_append.py
import sys
sys.path.append("C:/doit/Mymod")
--> 경로 이름을 추가해 해당 경로에 있는 모듈을 불러올 수 있음
pickle
객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈
객체를 바이너리 형태로 표현하고 저장하거나, 데이터를 파이썬 객체로 복원하는 protocols을 제공
pickle 모듈의 dump 함수를 사용하여 객체 data를 그대로 저장(serializing)
dump(obj, file_obj, ...) # Write the given Python object obj into file_obj
import pickle
f = open("test.txt", 'wb')
data = {1: 'python', 2: 'You need'}
pickle.dump(data, f)
f.close()
pickle.dump로 저장한 파일을 load함수를 사용해 객체 data로 복원(de-serializing)
load(file_obj, ...) # Read file_obj and return its Python object
import pickle
f = open("test.txt", 'rb')
data = picle.load(f)
print(data)
res : {1: 'python', 2: 'You need'}
import pickle
with open('text.txt'. 'rb') as f:
_, data = pickle.load(f)
print(data)
OS
환경 변수나 디렉토리, 파일 등의 OS 자원을 제어할 수 있게 해주는 모듈
os.environ
- 내 시스템의 환경변수 값을 알고 싶을 때 사용
>>> import os
>>> os.environ
environ({딕셔너리 객체}) # ('PROGRAMFILES': 'C:\\Program Files', ....) 이런식으로 나옴
- 돌려받은 객체가 딕셔너리 객체이기 때문에, 호출해서 원하는 값을 얻을 수도 있음
os.environ['PATH'] # res : 'C:\\ProgramData\\Oracle\\Java\\javapath; ... 생략 ...'
os.getcwd
os.getcwd() # res : 'C:\WINDOWS'
os.system
# 현재 디렉토리에서 시스템 명령어 ls을 실행하는 예
>>> os.system("ls")
os.popen
- 실행한 시스템 명령어의 결괏값을 읽기 모드 형태의 파일 객체로 돌려줌
f = os.popen("ls")
print(f.read())
기타 유용한 os 관련 함수
os.mkdir(디렉토리) : 디렉토리 생성
os.rmdir(디렉토리) : 디렉토리 삭제(비어있어야 가능)
os.unlink(파일 이름) : 파일을 지운다
os.rename(src, dst) : src라는 이름의 파일을 dst라는 이름으로 바꾼다.
shutil
- shutil.copy : 파일을 복사해주는 파이썬 모듈
# src.txt 파일을 dst.txt로 복사
import shutil
shutil.copy("src.txt", "dst.txt")
glob
Unix-style Pathname Pattern Expansion
특정 디렉토리에 있는 파일 이름을 모두 알아야 할 때 주로 사용하는 모듈
glob는 Unix shell 에서 사용되는 특정 패턴과 일치하는 파일과 디렉토리를 찾아줌
tempfile
파일을 임시로 만들어서 사용할 때 유용한 모듈
tempfile.mkstemp()
- 중복되지 않는 임시 파일의 이름을 무작위로 만들어서 돌려줌
import tempfile
filename = tempfile.mkstemp()
filename # res : 'C:\WINDOWS\TEMP\~-275151-0'
tempfile.TemporaryFile()
import tempfile
f = tempfile.TemporaryFile()
f.close() # 생성한 임시파일 자동으로 삭제
time
time.time()
- UTC를 사용하여 현재 시간을 실수 형태로 돌려주는 함수
- 1970/1/1 0시 00분 00초 epoch 시각부터 현재까지 흐른 시간을 second 로 리턴
import time
time.time() # res : 1692774508.134141
time.localtime / time.gmtime
- time.time()이 돌려준 실수 값을 사용해서 연도, 월, 일, 시, 분, 초... 의 형태로 바꿔주는 함수
- time.gmtime은 UTC 시간 기준으로 return
time.localtime(time.time())
# time.struct_time(tm_year=2023, tm_mon=11, ...)
time.gmtime(time.time())
# time.struct_time(tm_year=2023, tm_mon=11, ...)
time.asctime
- time.localtime에 의해서 반환된 튜플 형태의 값을 인수로 받아 날짜와 시간을 알아보기 쉬운 형태로 돌려주는 함수
time.asctime(time.localtime(time.time()))
# res: 'Wed Aug 23 16:10:47 2023'
time.ctime
time.ctime() # res : 'Wed Aug 23 16:10:47 2023'
time.process_time / time.thread_time
- 현재 프로세스 / 쓰레드 의 CPU 시간의 합을 return (sleep 시간 제외)
time.process_time() # 4.59375
time.thread_time() # 3.844024
time.strftime
import time
time.strftime('%x', time.localtime(time.time()))
# res : '08/23/23'
time.sleep
루프 안에서 주로 사용
일정한 시간 간격을 두고 루프를 실행할 수 있다.
주어진 시간동안 current thread의 실행을 중단시킬 수 있다.
# sleep1.py
import time
for i in range(10):
print(i)
time.sleep(1)
start = time.time()
time.sleep(2)
elapse = time.time() - start # 2.001231235...
calendar
파이썬에서 달력을 볼 수 있게 해주는 모듈
calendar.calendar(연도)
calendar.prcal(연도)
- calendar.calendar(연도)와 같은 결괏값
calendar.prmonth(연도, 월)
- 해당 연도의 해당 월에 해당하는 달력을 보여줌
calendar.weekday(연도, 월, 일)
그 날짜에 해당하는 요일 정보를 돌려줌
월요일은 0, 화요일은 1, .......
calendar.monthrange(연도, 월)
- 입력받은 달의 1일이 무슨 요일인지, 그 달이 며칠까지 있는 지를 튜플 형태로 돌려줌
import calendar
calendar.monthrange(2023, 8) # (calendar.TUESDAY, 31)
random
random.random()
- 0.0에서 1.0 사이의 실수 중에서 난수 값을 돌려줌
random.randint(a, b)
- a에서 b 사이의 정수 중에서 난수 값을 돌려줌(a, b 포함)
random.uniform(a, b)
- a에서 b 사이의 실수 중에서 난수 값을 돌려줌(a, b 포함)
random.gauss(mu, sigma), random.normalvariate(mu, sigma)
- 평균이 mu, 표준편차가 sigma인 Gaussian distribution을 따르는 분포 하에 난수(실수) 돌려줌
random.seed(a=None, version=2)
random.choice(iterable)
- 입력받은 변수에서 무작위로 하나를 선택하여 돌려줌
random.shuffle(list)
example
# random_pop.py
import random
def random_pop(data):
number = random.randint(0, len(data)- 1)
return data.pop(number)
import random
round2 = lambda x : int(x + 0.5)
print([round2(random.uniform(0, 10)) for i in range(10)])
print([round2(random.gauss(5, 1)) for i in range(10)])
webbrowser
threading
컴퓨터에서 동작하고 있는 프로그램을 Process라고 함
보통은 1개 프로세스는 한가지 일만 하지만, 스레드를 사용하여 하나의 프로세스 안에서 2가지 이상의 일을 동시에 수행할 수 있음
# origin.py
import time
def long_task():
for i in range(5):
time.sleep(1)
print(f'working: {i}\n')
print("Start")
for i in range(5):
long_task()
print("End")
# thread_test.py
import time
import threading
def long_task():
for i in range(5):
time.sleep(1)
print(f'working: {i}\n')
print("Start")
threads = []
for i in range(5):
t = threading.Thread(target = long_task) # Thread 생성
threads.append(t)
for t in threads:
t.start()
print("End")
math
- C의 math.h나 cmath 와 유사하게 유용한 수학 함수, 상수들을 제공
Constant
pi : 원주율 3.1415....
e : 자연상수 2.718....
nan
sqrt(x)
log(x[, base]), log2(x), log10(x)
- x의 natural 로그, base-2 로그, base-10 로그 값을 리턴
ceil(x)
- x와 같거나 그 이상인 가장 작은 수를 return
prod(iterable, *, start = 1)
- input iterable의 모든 요소들의 곱을 계산
sin(x), cos(x), tan(x).... atan(x), atan2(x,y)
degrees(x), radians(x)
isinf(x), isnan(x), isfinite(x)
- x가 infinity인지, NaN인지, finite 인지 혹은 아닌지 확인
import math
factorial_prod = lambda n : math.prod(range(1, n + 1))
print(factorial_prod(10)) # 3628800
decimal
빠르고 정확하게 rounded 소수점 산술을 제공
Decimal : floating point value를 담고 있는 클래스
Decimal.quantize(exp, rounding=None, context=None)
- exp 정확도를 가진 rounded value를 리턴
example
# without decimal library
print(round(3.5)) # 4
print(round(4.5)) # 4 (not 5)
- why? : systemic bias를 피하기 위해
import decimal
print(decimal.getcontext()) # rounding=decimal.ROUND_HALF_EVEN
print(decimal.Decimal(3.5).quantize(1, deciaml.ROUND_HALF_UP)) # 4
print(decimal.Decimal(4.5).quantize(1, deciaml.ROUND_HALF_UP)) # 5
# handmade function
round2 = lambda x : int (x + 0.5)
print(round2(3.5)) # 4
print(round2(4.5)) # 5
참조) Do it! 점프 투 파이썬 (박응용 지음)