티스토리 뷰

 

 

11. 표준 라이브러리 둘러보기 -- 2부

이 두 번쨰 둘러보기는 전문 프로그래밍 요구 사항을 지원하는 고급 모듈을 다루고 있다. 이러한 모듈들은 작은 스크립트에서는 거의 사용되지 않는다.

11.1 출력 포매팅

지난 학기 비지니스프로그래밍 시간에 1단원에서 가장 오랫동안 다룬 내용이다. 막 그렇게 중요한 내용은 아니지만 익혀두면 로그를 찍거나 CLI에서 정보를 보기 쉽게 출력할 수 있을 것이다.

  • reprlib 모듈의 repr() 함수는 많은 정보를 가지고있는 정보의 축약된 정보를 나타내는데 쓸 수 있다.

    import reprlib
    a = set('asgabqehrmkqleaiomklnpfw')
    print(a)                
    # {'w', 'f', 'q', 'o', 'l', 'b', 'r', 'e', 'i', 'a', 'p', 'h', 'm', 'n', 's', 'g', 'k'} 
    print(reprlib.repr(a))    # "{'a', 'b', 'e', 'f', 'g', 'h', ...}"
  • textwrap모듈은 너비(width)를 지정하여 그 너비에 맞게 텍스트를 포맷한다.

    import textwrap
    doc = """The wrap() method is just like fill() except that it returns
    a list of strings instead of one big string with newlines to separate
    the wrapped lines."""
    
    print(textwrap.fill(doc, width=40))
    """The wrap() method is just like fill()
    except that it returns a list of strings
    instead of one big string with newlines
    to separate the wrapped lines."""

11.2. 템플릿

  • string모듈은 토익 파트5 문제처럼 문장에 구멍을 뚫어놓고 필요한 정보를 넣는 템플릿을 만드는 Template 클래스를 포함한다.

  • 장고에서 html 파일들에서 변수들을 사용할 때 {{ varname }}이런식으로 썼는데 이것도 템플릿의 한 종류이지 않나 싶다.

  • 사용법은 자리표시자 이름 앞에 $를 붙이면 된다.

    from string import Template
    t = Template('I like $something')
    t.substitute(something='to drink')    # 'I like to drink'
  • 넣을 자리표시자 바로 뒤에 문자가 붙을경우는 {, }를 쓰면 된다.

    te = Template('Are you ${sirname}.Kim?')
    te.substitute(sirname='Mr')        # Are you Mr.Kim?
  • 템플릿 안에 $를 쓰려면 $$를 쓰면 된다.

    tem = Template('I only have $$$amount.')
    tem.substitute(amount='50')        # I only have $50.
  • substitute() 메소드는 자리표시자가 딕셔너리나 키워드 인자로 제공되지 않는 경우 KeyError를 일으킨다.

  • 데이터가 누락될 수도 있을 경우는 safe_substitute() 메서드를 사용하는게 적절할 수도 있다. 이 경우는 누락된 데이터의 자리표시자를 변경하지 않고 그대로 출력한다.

    temp = Template('Return the $item to $owner.')
    d = dict(item='apple')
    temp.substitute(d)
    """Traceback (most recent call last):
        ...
    KeyError: 'owner'"""
    temp.safe_substitute(d)        # 'Return the apple to the $owner.'

11.4. 다중 쓰레딩

  • 쓰레딩은 차례로 종속되지 않는 작업을 분리하는 기술이다. 쓰레드는 다른 작업이 백그라운데어서 돌고 앞에서는 사용자 입력을 받는 프로그램을 작성할 수 있다.

    import threading, zipfile
    
    class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
            threading.Thread.__init__(self)
            self.infile = infile
            self.outfile = outfile
    
        def run(self):
            f = zipfile.ZifFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
            f.write(self.infile)
            f.close()
            print('Finished background zip of:', self.infile)
    
    background = AsyncZip('mydata.txt', 'myarchive.zip')
    background = start()
    print('The main program continues to run in foreground.')
    
    background.join()        # Wait for the background task to finish
    print('Main program waited until background was done.')
  • 이것만 보고는 쓰레딩을 정확히 어떻게 사용하는지 모르겠으므로 다음에 쓰레드만 따로 다루겠다.

  • 다중 쓰레드 응용 프로그램의 가장 큰 문제점은 데이터 또는 다른 자원을 공유하는 쓰레드를 조정하는 것이다. 이를 위해 threading 모듈은 락, 이벤트, 조건 변수 및 세마포어를 비롯한 많은 수의 동기화 기본요소를 제공한다.

11.5. 로깅

  • logging모듈은 완전한 기능을 갖춘 유연한 로깅 시스템을 제공한다. 가장 단순한 경우, 로그 메시지는 파일이나 sys.stderr로 보내진다.

    import logging
    logging.debug('Debugging information')
    logging.info('Informational message')
    logging.warning('Warning:config file %s not found', 'server.conf')
    # WARNING:root:Warning:config file server.conf not found
    logging.error('Error occurred')
    # ERROR:root:Error occurred
    logging.critical('Critical error -- shutting down')
    # CRITICAL:root:Critical error -- shutting down

 

Reference: 파이썬 자습서

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함