Python with magic statement

Source: Internet
Author: User

Usually before we open the file is:

File = Open ("A.txt") Try:data = File.read () finally:file.close ()

* Close the file descriptor after each open file, but use the WITH statement instead:

Whih Open ("A.txt") as F:print F.readline ()

This is a good magic box with a default package that encapsulates the two functions of __enter__ and __exit__:

For our own class can also use with, as long as the class to add two function __enter__, __exit__ can:

>>> 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 Enter
In with
In exit


* You can see that when we use with the appropriate first call is the __ENTER__ function, and then do the following, after the end of the __exit__ function:


Write an operation similar to opening a file:

#!/usr/bin/env pythonclass 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 truewith demo (" Attr.py "," W ")  as f:    f.write (" Hello world ") performs the effect: [[email protected]  python]# python test_with.py attr.py whello world 

* Here the Open file is read, converted to print the incoming parameters and perform the operation with the write function inside.

In the __exit__ method, A,b,c, respectively, represents the exception type as value. Error, exception description, Traceback, when using return True, indicates that an exception is caught, and return false indicates that an exception is thrown.


Prompt for exception operation:

#!/usr/bin/env pythonclass 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 truewith demo ("a.py", "W")  as f:    f.write ("hello  World ")     iNT ("error") 

Execution effect:

[email protected] python]# python test_with.py a.py whello world<type ' exceptions. ValueError ' >invalid literal for int. () with base: ' Error ' <traceback object at 0xb3e3f8>


So with can help us to do a lot of repetitive operations, such as initializing, connecting to the database, shutting down the database, socket, and many other repeated operations.

For example, use the WITH syntax to hit the graphite socker listening port.

#!/usr/bin/python# coding:utf-8import errnoimport timeimport socketclass carbonclient (object):     def __init__ (Self, host, port):         self._host = host        self._port =  port        self._carbon = None         self._connected = none    def connect (self):          "" "              establishing a socket connection          ""          if not self._connected:             self._connect ()     def connected (self):         return&nBsp;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 ("{}  {} {}\n ". Format (Metric[0], metric[1], int (Time.time ()))                  elif len (Metric)  == 3:                      payload.append ("{}  {} {}\n ". 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,&NBSP;EXEC_TYPE,&NBSP;EXEC_VALUE,&NBSP;EXC_TB):         self.close ()         return exec_value is  noneclass rebootCarbonclient (carbonclient):    reboot_carbon_addr =  ("192.168.1.54",  2003)     def __init__ (self):         super ( rebootcarbonclient, self). __init__ (*self. REBOOT_CARBON_ADDR) "" "    1 Strip:         (key,  Value, time)          (key, value)      multiple         [(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 ')])



This article is from the "Little Luo" blog, please be sure to keep this source http://xiaoluoge.blog.51cto.com/9141967/1760484

Python with magic statement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.