python with 마법 문구

4879 단어 filepythonwithin
보통 이전에 우 리 는 파일 을 열 때:
file = open("a.txt")
try:  
  data = file.read()
finally:    
   file.close()

*파일 을 열 때마다 파일 설명 자 를 닫 지만 with 문 구 를 사용 하면 사용 하지 않 습 니 다.
whih open("a.txt") as f:
   print f.readline()

이것 은 with 가 기본적으로 봉 인 된 좋 은 마법 상자 입 니 다.봉 인 했 습 니 다enter__와exit__두 함수:
우리 자신의 클래스 를 위해 서도 with 를 사용 할 수 있 습 니 다.이 클래스 에 두 개의 함수 만 추가 하면enter__, __exit__바로:
>>> class A:...      def __enter__(self):...         print "in enter"...      def __exit__(self, a, b, c):...         print "in exit">>> with A() as a:          ...     print "in with"
... in enterin within exit
*우리 가 with 를 사용 할 때 가장 먼저 호출 할 수 있 는 것 은enter__함수,그리고 아래 작업 을 진행 하고 끝 난 후에 야exit__함수:
파일 을 여 는 것 과 같은 동작 을 쓰 십시오:
#!/usr/bin/env python
class demo:
    def __init__(self, path, mode):
        self.path = path
        self.mode = mode
    def __enter__(self):
        return self
    def write(self, text):
        print self.path,self.mode
        print(text)
    def __exit__(self, a, b ,c):
        return True
with demo("attr.py","w") as f:
    f.write("hello world")

    :
[root@monitor python]# python test_with.py 
attr.py w
hello world

*여 기 는 열 린 파일 을 읽 고 들 어 오 는 인자 로 변환 하고 with 에 write 함 수 를 실행 합 니 다.
__exit__방법 중의 a,b,c 는 각각 value.Error,이상 설명,Traceback 와 같은 이상 유형 을 나타 낸다.return True 를 사용 할 때 이상 을 잡 을 수 있다 고 표시 하고 return False 에 서 는 이상 을 던 질 수 있다 고 표시 합 니 다.
알림 이상 동작:
#!/usr/bin/env python
class demo:
    def __init__(self, path, mode):
        self.path = path
        self.mode = mode
    def __enter__(self):
        return self
    def write(self, text):
        print self.path,self.mode
        print(text)
    def __exit__(self, a, b ,c):
        print a
        print b
        print c
        return True
with demo("a.py","w") as f:
    f.write("hello world")
    int("error")

실행 효과:
[root@monitor python]# python test_with.py 
a.py w
hello world

invalid literal for int() with base 10: 'error'

이렇게 with 는 우리 가 많은 중복 작업 을 완성 하 는 데 도움 을 줄 수 있다.예 를 들 어 초기 화,데이터 베 이 스 를 연결 하고 데이터 베 이 스 를 닫 는 것 이다.socket 등 여러 중복 작업.
예 를 들 어 with 문법 으로 graphite 의 socker 감청 포트 에 데 이 터 를 칩 니 다.
#!/usr/bin/python
# coding:utf-8
import errno
import time
import socket
class CarbonClient(object):
    def __init__(self, host, port):
        self._host = host
        self._port = port
        self._carbon = None
        self._connected = None
    def connect(self):
        """
              socket  
        """
        if not self._connected:
            self._connect()
    def connected(self):
        return self._connected
    def _connect(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while 1:
            try:
                sock.connect((self._host, self._port))
            except socket.error as e:
                if e.errno == errno.EINTR:
                    continue
                else:
                    raise e
            break
        self._carbon = sock
        self._connected = True
    def close(self):
        if self._connected:
            self._carbon.close()
            self._connected = False
    def send(self, metrics):
        chunk_start, chunk_end = 0,20
        while 1:
            payload = []
            metrics_chunk = metrics[chunk_start: chunk_end]
            if not metrics_chunk:
                break
            for metric in metrics_chunk:
                if len(metric) == 2:
                    payload.append("{} {} {}
".format(metric[0], metric[1], int(time.time())))                 elif len(metric) == 3:                     payload.append("{} {} {}
".format(*metric))                 else:                     raise ValueError("Error format data")             self._carbon.sendall("".join(payload))             chunk_start, chunk_end = chunk_end, chunk_end + 20     def __enter__(self):         self.connect()         return self     def __exit__(self, exec_type, exec_value, exc_tb):         self.close()         return exec_value is None class RebootCarbonClient(CarbonClient):     REBOOT_CARBON_ADDR = ("192.168.1.54", 2003)     def __init__(self):         super(RebootCarbonClient, self).__init__(*self.REBOOT_CARBON_ADDR) """     1 :         (key, value, time)         (key, value)              [(key, value), (key, value)] graphite api """ if __name__ == "__main__":     with RebootCarbonClient() as client:         client.send([("hostname.sys.mem.usage", '1096'), ("hostname.sys.mem.usage", '2048')])

좋은 웹페이지 즐겨찾기