python with 마법 문구
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')])
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
4줄의 PHP에서 CSV 파일을 구문 분석하는 방법은 무엇입니까?CSV는 데이터를 애플리케이션에 통합하기 위한 표준 형식입니다. 그렇게 할 때 종종 이 형식을 기반으로 데이터를 가져와야 합니다. PHP는 파일을 열고 CSV 행을 구문 분석하는 기본 기능과 함께 제공됩니다. 파일c...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.