기본 콘텐츠로 건너뛰기

라벨이 python인 게시물 표시

[python] working directory설정하는 방법

이번에는 파이썬에서 가끔 삽질을 유도하는 path문제에 대해서 알아보고자 한다. 모듈을 나눠서 개발을 하다보면 서로의 개발환경을 맞추지 않고 작업을 할 수 밖에 없는 경우가 있다. 툴, 파이썬 버전, 등 개인적인 이유에서 셋팅을 맞추지 않고 개발을 시작을 하는 경우가 있습니다. 또한 갑자기 두개의 프로젝트가 갑자기 합쳐져야 하는 경우도 있습니다. (필자는 대부분 이러한 경우때 문제가 발생하였습니다.) 이럴떄 가장 많은 문제가 되는것이 바로 path문제입니다. path도 여러가지 문제가 있을 수 있는데 file을 접근할 떄 생가는 문제에 대해서 다뤄보고자 합니다. import os os . chdir ( os . getcwd () + '/WORKING DIRECTORY' ) 외부 모듈을 가져다가 쓰는 파일에서 해당 코드만 추가시켜주면 간단히 path문제를 해결 할 수 있습니다. 해당 코드는 working directory를 설정하여 절대경로를 고정시켜주는 역할을 합니다. 즉 해당 모듈을 어디에서 호출을 하든 절대경로를 해당 경로로 고정이 됩니다.

[python] 제너레이터(generator)를 통해 효율적인 코드작성

오늘은 generator에 대해서 알아볼까 합니다 우선 generator는 python말고도 javascript es6에서도 새롭게 추가된 부분이기도 합니다. 우선 python docs의 generator에 대한 정의를 봅시다. generator A function which returns an ierator. It looks like a normal function except that it comtains yield statements for producting a series of values usable in a for-loop that can be retrieved one at a time with the next() function. Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator resumes, it picks-up where it left-off (in contrast to functions which start fresh on every invocation). 첫 줄에 한 줄로 정의가 됐다.  반복자를 반환하는 함수 모든 호출에서 새롭게 시작되는 함수가 아닌 위치를 기억하는 함수 즉 특정 위치를 기억하여 루프를 돌릴 수 있도록 반환을 하는 것이다. 해당 함수는 next()를 이용하여 호출이 가능. 간단한 코드를 통해 generator의 사용방법을 알아보자. # app.py def generator(n): i = 0 while i < n: yield i i += 1 _generator = generator(10) print(_generator) for i in _generator: print(

[python] 간단한 getter와 setter를 구현할 때는 property, 복잡해질 경우 descriptor를 사용하자

http://meonggae.blogspot.kr/2016/11/python-getter-setter-property-setter.html 필자가 전에 한번 getter와 setter에 관련되서 글을 쓴 적이 있다. 이때 getter와 setter함수를 구현하지 말고 @property를 이용해서 구현을 하라고 했다 하지만 코드를 작성하다보면 @property가 복잡해지는 경우가 발생을 할 것이다. 이럴떄는 descriptor를 사용을 하여 코드를 좀더 깔끔하게 할 수 있다. class test: @property def t(self): return self._t @t.setter def t(self, value): print('setter 작동') self._t = 10 a = test() a.t = 10 property를 이용하여 코드를 작성을 할 수 있습니다. property를 이용하영 외부에서 _t를 접근 할 수 있도록 하였습니다. $ python3 app.py setter 작동 외부에서 t를 접근 할 때 정상적으로 t()가 실행 됬음을 확인 할 수 있습니다. 그런데 이는 외부 뿐 아니라 내부에서 접근을 할 때에도 실행이 됩니다. class test: def __init__(self): self.t = 1 @property def t(self): return self._t @t.setter def t(self, value): print('setter 작동') self._t = 10 a = test() a.t = 10 해당 코드를 실행을 시켜봅시다. $ python3 app.py setter작동 setter작동 t()가 두번 실행됬습니다. test()에서 __init__이 호출이 되면서 내부적으로 self

[python] datetime을 이용하여 utc값 가져오기

datetime을 이용하여 utc값을 가져와보자 import datetime def get_time(): now_utc = datetime.datetime.utcnow() return now_utc.strftime('%s') def get_utc_convert(): return (datetime.datetime.utcnow() + datetime.timedelta(hours=9)).strftime('%Y-%m-%d') get_time은 utc값을 가져와 준다. get_utc_convert는 utc값을 서울 시간 기준을 맞추어 가져와 준다. datetime은 type이 datetime이기 때문에 str으로 변환하여 사용하는 것이 안전하다

[git] pylint, pep8를 사용하여 코드스타일 검사

프로젝트의 규모가 커질수록 코드 스타일 통일이 매우 중요합니다. python에서는 pylint와 pep8을 사용하여 스타일 검사가 다릅니다. 엄밀히 따지면 이둘은 약간 성격이 다릅니다. 우선 pylint에 대해서 먼저 알아보도록 하겠습니다. $ vim app.py import requests as rq def test(): print('test') if __name__ == "__main__": test() $ pylint app.py ************* Module app W:  4, 0: Found indentation with tabs instead of spaces (mixed-indentation) W:  7, 0: Found indentation with tabs instead of spaces (mixed-indentation) C:  1, 0: Missing module docstring (missing-docstring) C:  3, 0: Missing function docstring (missing-docstring) W:  1, 0: Unused requests imported as rq (unused-import) ... 중략 3종류의 메시지가 출력이 됩니다. 1. 탭을 사용하지 않고 스페이스를 사용 2. docstring을 사용하지 않음 3. 사용하지 않는 모듈을 import docstring이란? docstring은 modlue, class, function의 설명을 작성하는 부분입니다. python에서는 ''' 설명... :parameter {type} : 설명 :return {type} : 설명 ''' 의 형태로 작성이 됩니다. 그럼 위의 메시지를 바탕으로 수정을 해보도록 하겠습니다. $ vim app.p

[python] decorator를 이용하여 함수 확장

python에서는 @라는 키워드를 이용해서 decorator라는 기능을 쓰면 함수의 기능을 확장하여 사용 할 수 있다. python에서도 javascript와 동일하게 함수를 일급객체 취급을 한다. 즉 함수를 변수에 담아서 인자로 넘길 수 있다는 의미가 된다. 이제 decorator의 기능에 대해서 알아보자.  함수를 다른 함수의 기능을 덧 붙일수 있고, 클래스의 기능을 덧 붙일수 있다. 첫번쨰로 함수의 기능을 덧 붙여보자. 1 . function p.py 1 2 3 4 5 6 7 8 9 10 11 12 13 def  decorator_test(func):      def  new_func():          print  ( "Begin" )         func()          print  ( "End" )      return  new_func   @decorator_test def  ppp():      print ( 'test' )     ppp() cs p1.py 1 2 3 4 5 6 7 8 9 10 11 12 13 def  decorator_test(func):      def  new_func():          print  ( "Begin" )         func()          print  ( "End" )      return  new_func   # @decorator_test def  ppp():      print ( 'test' )   test  =  decorator_test(ppp) test() cs $python p.py >>> Begin

[python] classmethod와 abstractmethod

classmethod와 abstractmethod를 비슷한 방법으로 사용을 할 수 있다. 우선 classmethod와 비교가 되는것이 staticmethod이다. 간단하게 classmethod와 staticmethod가 어떤건지 부터 비교를 해보자. @ staticmethod p.py 1 2 3 4 5 6 7 8 9 10 11 12 class  MethodTest(object):     __c_test  =   1      def  __init__(self):          pass       @staticmethod      def  s_print():          print ( 'is staticmethod' )   MethodTest.s_print() MethodTest.s_print() MethodTest.s_print() cs $python p.py >>> is staticmethod is staticmethod is staticmethod staticmethod는 해당 클래스를 namespace처럼 사용하기 위해 사용을 한다. 즉 해당 객체를 생성하지 않아도 해당 클래스 이름만 가지고 해당 method를 호출을 할 수있다. staticmethod는 self인자를 받지 않는다. @ classmethod p.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class  MethodTest(object):     __c_test  =   1      def  __init__(self):          pass       @classmethod      def  c_print(cls):         cls.__c_test  + =   1