First, scene reproduction
In Python, when we open a file, for the robustness of the code, we usually consider some exceptions, such as:
Try : = Open ('/path/data') = ccfile.readlines () ccfile.close () except IOError: log.write ('no data read\n')
If there is an exception to the file operation, write an error log;
Consider a situation where if the file is opened successfully, but the ReadLines () call fails, the exception handling immediately jumps to except execution, so that the file is closed without a chance to be executed.
One solution is to put the close () statement in the finally clause, and finally the feature is that it will be executed regardless of the exception.
Try : Try : = Open ('/path/data') = ccfile.readlines () except IOError: log.write ('no data read\n') Finally ccfile.close ()
Or
Try : Try : = Open ('/path/data') = ccfile.readlines () finally IOError: ccfile.close ()except IOError: log.write (' No data read\n ')
But the above statement is not elegant. You can use the WITH statement:
With open ('/etc/passwd') as F: for in f: Print (line)
Second, with statement
1. The WITH statement can only be used on objects that support the context management protocol. Objects that support this agreement
Filedecimal. Contextthread.LockTypethreading.Lockthreading.RLockthreading.Conditionthreading.Semaphorethreading.BoundedSemaphore
2. Parsing with statement execution:
With context_expr () as Var:
DoSomething ()
- When the WITH statement executes, the context expression (context_expr) (typically a method) is executed to obtain a context manager object, and the context manager's responsibility is to provide a context object for handling the details in the WITH statement block:
- Once the context object is acquired, its __enter__ () method is called, and all preparations for the WITH statement block are completed, and if the WITH statement follows the AS statement, the return value of the __enter__ () method is used to assign the value;
- When the WITH statement block ends, whether it is a normal end, or because of an exception, the __exit__ () method of the context object is called, the __exit__ () method has 3 parameters, and if the With statement ends normally, all three parameters are none; If an exception occurs, The values of the three parameters are equal to the three values returned by the call to the Sys.exc_info () function: Type (Exception Class), value (exception instance), and trace record (Traceback), corresponding to the tracking Record object.
- Because the context manager primarily acts on shared resources, the __enter__ () and __exit__ () methods basically complete the low-level work of allocating and releasing resources, such as: Database connections, lock allocations, semaphore plus/minus, state management, File open/Close, exception handling, and so on.
3. Custom classes use with to manage
classA (object):def __enter__(self):Print('__enter__ () called') return SelfdefPrint_hello (self):Print("Hello world!") def __exit__(self, e_t, E_v, t_b):Print('__exit__ () called')#The __enter__ method is executed firstWith a () as a:#A is the return object of __enter__A.print_hello ()Print('got instance')#End will execute __exit__ method
Output Result:
__enter__ () Calledhello World!got instance __exit__ () called
Iii. Contextlib module for automatic context management
@contextmanagerdefcontext ():Print('Entering the zone') Try: yield exceptException as E:Print('With an error%s'%e)RaiseeElse: Print('With no error') with context ():Print('----in context call------')
Output:
Entering the zone---- in context------withno error
Source: http://www.cnblogs.com/chenny7/p/4213447.html
Python with statements