Exception / File / Log Handling

κΉ€μ„ μž¬Β·2021λ…„ 12μ›” 12일
0

AI Tech

λͺ©λ‘ 보기
2/8
post-thumbnail

πŸ’‘ 생각해보기
ν”„λ‘œκ·Έλž¨ μ‚¬μš©ν•  λ•Œ μΌμ–΄λ‚˜λŠ” 였λ₯˜λ“€

  • μ£Όμ†Œλ₯Ό μž…λ ₯ν•˜μ§€ μ•Šκ³  배솑 μš”μ²­
  • μ €μž₯도 μ•ˆ ν–ˆλŠ”λ° 컴퓨터 전원이 λ‚˜κ°
  • κ²Œμž„ μ•„μ΄ν…œ μƒ€λŠ”λ° κ²Œμž„μ—μ„œ νŠ•κΉ€
  • μ˜ˆμƒμΉ˜ λͺ»ν•œ λ§Žμ€ 일( μ˜ˆμ™Έ ) 듀이 생김

Exception

μ˜ˆμƒ κ°€λŠ₯ν•œ μ˜ˆμ™Έ

  • λ°œμƒ μ—¬λΆ€λ₯Ό 사전에 인지할 수 μžˆλŠ” μ˜ˆμ™Έ
  • μ‚¬μš©μžμ˜ 잘λͺ»λœ μž…λ ₯, 파일 호좜 μ‹œ 파일 μ—†μŒ
  • κ°œλ°œμžκ°€ λ°˜λ“œμ‹œ λͺ…μ‹œμ μœΌλ‘œ μ •μ˜ ν•΄μ•Όν•œλ‹€

μ˜ˆμƒ λΆˆκ°€λŠ₯ν•œ μ˜ˆμ™Έ

  • 인터프리터 κ³Όμ •μ—μ„œ λ°œμƒν•˜λŠ” μ˜ˆμ™Έ, 개발자 μ‹€μˆ˜
  • 리슀트의 λ²”μœ„λ₯Ό λ„˜μ–΄κ°€λŠ” κ°’ 호좜, μ •μˆ˜ 0으둜 λ‚˜λˆ„λŠ” 경우
  • μˆ˜ν–‰ λΆˆκ°€μ‹œ 인터프리터가 μžλ™ 호좜
  • μ˜ˆμ™Έκ°€ λ°œμƒν•  경우 후속 쑰치 λ“± λŒ€μ²˜κ°€ ν•„μš”ν•˜λ‹€

    1) μ—†λŠ” 파일 호좜 -> 파일 μ—†μŒμ„ μ•Œλ¦Ό
    2) κ²Œμž„ 이상 μ’…λ£Œ -> κ²Œμž„ 정보 μ €μž₯
    ✨ ν”„λ‘œκ·Έλž¨ = μ œν’ˆ, λͺ¨λ“  잘λͺ»λœ 상황에 λŒ€μ²˜κ°€ ν•„μš”ν•˜λ‹€( Exception Handling )

파이썬의 μ˜ˆμ™Έ 처리

πŸ“ try ~ except 문법

try:
	# μ˜ˆμ™Έ λ°œμƒ κ°€λŠ₯ μ½”λ“œ
except <Exception Type>:
	# μ˜ˆμ™Έ λ°œμƒμ‹œ λŒ€μ‘ν•˜λŠ” μ½”λ“œ

πŸ“ 0으둜 숫자λ₯Ό λ‚˜λˆŒ λ•Œ μ˜ˆμ™Έμ²˜λ¦¬ ν•˜κΈ°

for i in range(10):
	try:
    	print(10 / i)
    except ZeroDivisionError:
    	print('Not divided by 0')

πŸ“ Built-in Exception( 기본적으둜 μ œκ³΅ν•˜λŠ” μ˜ˆμ™Έ )

파이썬의 μ˜ˆμ™Έ 처리 μ˜ˆμ‹œ

πŸ“ μ˜ˆμ™Έ 정보 ν‘œμ‹œν•˜κΈ°

for i in range(10):
	
    try:
    	print(10 / i )
    except ZeroDivistionError as e:
    	print(e)
        print('Not divided by 0')

πŸ“ try ~ except ~ else

try:
	# μ˜ˆμ™Έ λ°œμƒ κ°€λŠ₯ μ½”λ“œ
except <Exception Type>:
	# μ˜ˆμ™Έ λ°œμƒμ‹œ λ™μž‘ν•˜λŠ” μ½”λ“œ
else:
	# μ˜ˆμ™Έκ°€ λ°œμƒν•˜μ§€ μ•Šμ„ λ•Œ λ™μž‘ν•˜λŠ” μ½”λ“œ
for i in range(10):
	try:
		result = 10 / i
    except ZeroDivisionError:
    	print('Not divided by 0')
    else:
    	print(10 / i)

πŸ“ try ~ except ~ finally

try:
	# μ˜ˆμ™Έ λ°œμƒ κ°€λŠ₯ μ½”λ“œ
except <Exception Type>:
	# μ˜ˆμ™Έ λ°œμƒμ‹œ λ™μž‘ν•˜λŠ” μ½”λ“œ
finally:
	# μ˜ˆμ™Έ λ°œμƒ 여뢀와 상관없이 μ‹€ν–‰
try:
	for i in range(1, 10):
    	result = 10 // i
        print(result)
except ZeroDivisionError:
	print('Not divided by 0')
finally:
	print('μ’…λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€')

πŸ“ raise

  • ν•„μš”μ— 따라 κ°•μ œλ‘œ Exception을 λ°œμƒ
raise < Exception Type> ( μ˜ˆμ™Έμ •λ³΄ )
while True:
	value = input('λ³€ν™˜ν•  μ •μˆ˜ 값을 μž…λ ₯ν•΄μ£Όμ„Έμš”')
    for digit in value:
    	if digit not in '0123456789':
        	raise ValueError('μˆ«μžκ°’μ„ μž…λ ₯ν•˜μ§€ μ•ŠμœΌμ…¨μŠ΅λ‹ˆλ‹€')
    print('μ •μˆ˜κ°’μœΌλ‘œ λ³€ν™˜λœ 숫자 -', int(value))

πŸ“ assert

  • νŠΉμ • 쑰건에 λ§Œμ‘±ν•˜μ§€ μ•Šμ„ 경우 μ˜ˆμ™Έ λ°œμƒ
assert μ˜ˆμ™Έμ‘°κ±΄
def get_binary_number(decimal_number):
	assert isinstance(decimal_number, int)
    return bin(decimal_number)
    
print(get_binary_number(10))

File Handling

  • File system, 파일 μ‹œμŠ€ν…œ
  • OSμ—μ„œ νŒŒμΌμ„ μ €μž₯ν•˜λŠ” 트리ꡬ쑰 μ €μž₯ 체계

파일의 κΈ°λ³Έ 체계 πŸ‘‰ 파일 vs 디렉토리

디렉토리( Directory)

  • 폴더 λ˜λŠ” λ””λ ‰ν† λ¦¬λ‘œ 뢈림
  • 파일과 λ‹€λ₯Έ 디렉토리λ₯Ό 포함할 수 μžˆλ‹€

파일( File )

  • μ»΄ν“¨ν„°μ—μ„œ 정보λ₯Ό μ €μž₯ν•˜λŠ” 논리적인 λ‹¨μœ„
  • νŒŒμΌμ€ 파일λͺ…κ³Ό ν™•μž₯자둜 식별
  • μ‹€ν–‰, μ“°κΈ°, 읽기 등을 ν•  수 있음

파일의 μ’…λ₯˜

  • 기본적인 파일 μ’…λ₯˜λ‘œ text파일과 binary파일둜 λ‚˜λˆ”
  • μ»΄ν“¨ν„°λŠ” textνŒŒμΌμ„ μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ binary 파일둜 λ³€ν™˜μ‹œν‚΄
  • λͺ¨λ“  text νŒŒμΌλ„ μ‹€μ œλŠ” binary파일,
  • ASCII/Unicode λ¬Έμžμ—΄ μ§‘ν•©μœΌλ‘œ μ €μž₯λ˜μ–΄ μ‚¬λžŒμ΄ 읽을 수 μžˆλ‹€

πŸ“ python file I/O

  • νŒŒμ΄μ¬μ€ 파일 처리λ₯Ό μœ„ν•΄ open ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©
f = open('<파일 이름>', 'μ ‘κ·Ό λͺ¨λ“œ')
f.close()

  • read() txt 파일 μ•ˆμ— μžˆλŠ” λ‚΄μš©μ„ λ¬Έμžμ—΄λ‘œ λ°˜ν™˜
f = open('i_have_a_dream.txt', 'r')
contents = f.read()
print(contents)
f.close()
  • with ꡬ문과 ν•¨κ»˜ μ‚¬μš©ν•˜κΈ°
with open(i_have_a_dream.txt', 'r') as my_file:
	contents = my_file.read()
    print(type(contents), contents)

πŸ“ 파이썬의 File Read

  • ν•œ 쀄씩 읽어 List Type으둜 λ°˜ν™˜
with open('i_have_a_dream.txt', 'r') as my_file:
	content_list = my_file.readlines()	# 파일 전체λ₯Ό list둜 λ°˜ν™˜
    print(type(content_list))	# Type 확인
    print(content_list)	# 리슀트 κ°’ 좜λ ₯
  • μ‹€ν–‰ μ‹œ λ§ˆλ‹€ ν•œ 쀄 μ”© 읽어 였기
with open('i_have_a_dream.txt', 'r') as my_file:
	i = 0
    while True:
    	line = my_file.readline()
        if not line:
        	break
        print(str(i) + '===' + line.replace('\n', ''))	# ν•œμ€„μ”© κ°’ 좜λ ₯
        i += 1
  • 단어 톡계 정보 μ‚°μΆœ
with open("i_have_a_dream.txt", "r") as my_file:
    contents = my_file.read()
    word_list = contents.split(" ") 
    #빈칸 κΈ°μ€€μœΌλ‘œ 단어λ₯Ό 뢄리 리슀트
    line_list = contents.split("\n") 
    #ν•œμ€„ μ”© λΆ„λ¦¬ν•˜μ—¬ 리슀트

print("Total Number of Characters :", len(contents))
print("Total Number of Words:", len(word_list))
print("Total Number of Lines :", len(line_list))
  • modeλŠ” w, encoding=utf8
f = open("count_log.txt", 'w', encoding="utf8")
for i in range(1, 11):
    data = "%d번째 μ€„μž…λ‹ˆλ‹€.\n" % i
    f.write(data)
f.close()
  • modeaλŠ” μΆ”κ°€λͺ¨λ“œ
with open("count_log.txt", 'a', encoding="utf8") as f:
for i in range(1, 11):
	data = "%d번째 μ€„μž…λ‹ˆλ‹€.\n" % i
f.write(data)

파이썬의 directory 닀루기

πŸ“ os λͺ¨λ“ˆμ„ μ‚¬μš©ν•˜μ—¬ Directory 닀루기

import os
os. mkdir('log')

πŸ“ 디렉토리가 μžˆλŠ”μ§€ ν™•μΈν•˜κΈ°

if not os.path.isdir('log'):
	os.mkdir('log')

Log 파일 μƒμ„±ν•˜κΈ°

  • 디렉토리가 μžˆλŠ”μ§€
  • 파일이 μžˆλŠ”μ§€ 확인 ν›„
import os

if not os.path.isdir('log'):
	os.mkdir('log')
if not os.path.exists('log/count_log.txt'):
	f = open('log/count_log.txt', 'w', encoding='utf8')
    f.write('기둝이 μ‹œμž‘λ©λ‹ˆλ‹€\n')
    f.close()
    
with open('log/count_log.txt', 'a', encoding='utf8') as f:
	import random, datetime
    for i in range(1, 11):
    stamp = str(datetime.datetime.now())
    value = random.random() * 1000000
    log_line = stamp + '\t' + str(value) +'값이 μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€' + '\n'
    f.write(log_line)

pickle

  • 파이썬의 객체λ₯Ό μ˜μ†ν™”( persistence )ν•˜λŠ” built-in 객체
  • 데이터, objectλ“± 싀행쀑 정보λ₯Ό μ €μž₯ -> λΆˆλŸ¬μ™€μ„œ μ‚¬μš©
  • μ €μž₯ν•΄μ•Όν•˜λŠ” 정보, 계산 κ²°κ³Ό( λͺ¨λΈ ) λ“± ν™œμš©μΌ λ§Žλ‹€
import pickle

f = open('list.pickle', 'wb')
test = [1, 2, 3, 4, 5]
pickle.dump(test, f)
f.close()
f = open(list.pickle', 'rb')
test_pickle = pickle.load(f)
print(test_pickle)
f.close()

Logging Handling

둜그 남기기 - Logging

  • ν”„λ‘œκ·Έλž¨μ΄ μ‹€ν–‰λ˜λŠ” λ™μ•ˆ μΌμ–΄λ‚˜λŠ” 정보 기둝을 남기기
  • μœ μ €μ˜ μ ‘κ·Ό, ν”„λ‘œκ·Έλž¨μ˜ Exception, νŠΉμ • ν•¨μˆ˜μ˜ μ‚¬μš©
  • console 화면에 좜λ ₯, νŒŒμΌμ— 남기기, DB에 남기기 λ“±
  • 기둝된 둜그λ₯Ό λΆ„μ„ν•˜μ—¬ μ˜λ―ΈμžˆλŠ” κ²°κ³Όλ₯Ό λ„μΆœ ν•  수 μžˆλ‹€
  • μ‹€μƒμ‹œμ μ—μ„œ λ‚¨κ²¨μ•Όν•˜λŠ” 기둝, κ°œλ°œμ‹œμ μ—μ„œ λ‚¨κ²¨μ•Όν•˜λŠ” 기둝이 μžˆλ‹€
  • 기둝을 print둜 λ‚¨κΈ°λŠ” 것도 κ°€λŠ₯함
  • κ·ΈλŸ¬λ‚˜ Console μ°½μ—λ§Œ λ‚¨κΈ°λŠ” 기둝은 λΆ„μ„μ‹œ μ‚¬μš©λΆˆκ°€
  • λ•Œλ‘œλŠ” λ ˆλ²¨λ³„( 개발, 운영 )둜 기둝을 남길 ν•„μš”λ„ μžˆλ‹€
  • λͺ¨λ“ˆλ³„λ‘œ λ³„λ„μ˜ logging을 λ‚¨κΈΈν•„μš”λ„ μžˆλ‹€
  • μ΄λŸ¬ν•œ κΈ°λŠ₯을 μ²΄κ³„μ μœΌλ‘œ μ§€μ›ν•˜λŠ” λͺ¨λ“ˆμ΄ ν•„μš”!!

logging λͺ¨λ“ˆ

import logging

logging.debug("ν‹€λ Έμž–μ•„!")
logging.info("확인해")
logging.warning("쑰심해!")
logging.error("μ—λŸ¬λ‚¬μ–΄!!!")
logging.critical ("λ§ν–ˆλ‹€...")

logging level

  • ν”„λ‘œκ·Έλž¨ 진행 상황에 따라 λ‹€λ₯Έ Level의 Logλ₯Ό 좜λ ₯
  • 개발 μ‹œμ , 운영 μ‹œμ  λ§ˆλ‹€ λ‹€λ₯Έ Logκ°€ 남을 수 μžˆλ„λ‘ 지원
  • DEBUG > INFO > WARNING > ERROR > Critical
  • Log κ΄€λ¦¬μ‹œ κ°€μž₯ 기본이 λ˜λŠ” μ„€μ • 정보

configparser

  • ν”„λ‘œκ·Έλž¨μ˜ μ‹€ν–‰ 섀정을 file에 μ €μž₯
  • Section, Key, Value κ°’μ˜ ν˜•νƒœλ‘œ μ„€μ •λœ μ„€μ • νŒŒμΌμ„ μ‚¬μš©
  • μ„€μ •νŒŒμΌμ„ Dict type으둜 호좜 ν›„ μ‚¬μš©
import configparser

config = configparser.ConfigParser()
config.sections()

config.read('example.cfg')
config.sections()

for key in condig['SectionOne']:
	print(key)
    
config['SectionOne']['status']

argparser

  • Console μ°½μ—μ„œ ν”„λ‘œκ·Έλž¨ μ‹€ν–‰μ‹œ Setting 정보λ₯Ό μ €μž₯
  • 거의 λͺ¨λ“  Console 기반 Python ν”„λ‘œκ·Έλž¨ 기본으둜 제곡
  • 특수 λͺ¨λ“ˆλ„ 많이 μ‘΄μž¬ν•˜μ§€λ§Œ( TF ), 일반적으둜 argparseλ₯Ό μ‚¬μš©
  • Command-Line Option 이라고 λΆ€λ₯Έλ‹€
profile
data science!!, data analyst!! ///// hello world

0개의 λŒ“κΈ€