To use the WITH statement, you first understand the concept of the context manager. With the context manager, the WITH statement can work. The following is a set of concepts related to the context manager and with statements.
context Management Protocol : Contains methods __enter__ () and __exit__ (), supports The object of this Protocol is to implement both methods.
context Manager : An object that supports the context management protocol, which implements the __enter__ () and __exit__ () methods. The context manager defines the run-time context to be established when the WITH statement is executed, and the
can also be used by calling its methods directly. runtime context (runtime Contexts) : Created by the context manager, through the context Manager's __enter__ () and
__exit__ () method is implemented, and the __enter__ () method enters the runtime context before the statement body executes, __exit__ () in exit from run-time context after execution of the statement body. The With statement supports the concept of a run-time context. context expression" : The expression following the keyword with in the WITH statement, which
Statement Body (with-body): A block of code wrapped with a statement that invokes the context tube before executing the statement body
The __enter__ () method of the manager executes the __exit__ () method after the statement body is executed.
#-----*-coding:utf-8-*-----"" "Python ' s with statement is first introduced five years ago, in Python 2.5. It's handy when you have the related operations which you ' d as-to-execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing It:with open (' Output.txt ', ' W ') as F:f.writ E (' Hi there! ') The above with statement would automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement are that it's guaranteed to close the file no matter how the nested block exits. If An exception occurs before the end of the block, it would close the file before the exception is caught by an outer exce Ption handler. If the nested block were to contain a return statement, or a continue or break statement, the WITH statement would automa Tically close the file in those cases, too. "" f = open ("Numbers.txt", "W") F.write ("Hello") f.close () with open ("NUmbers.txt "," W ") as F:f.write (" Hello ") F = open (" Numbers.txt ") print dir (f) Import Osclass chdir:def __init__ (self, DIR): Self.dir = dir print "__init__" def __enter__ (self): print "__enter__" Self.olddir = OS.GETCWD () Os.chdir (Self.dir) return self def __exit__ (self, *a): print "__exit__" Os.chdi R (self.olddir) print os.getcwd () print "Before with" with chdir ("/tmp") as X:print os.getcwd () print "After with" Print OS. GETCWD () "Problem Write a context manager capture_output to capture stdout inside a with Block.with capture_output () as B Uf:print "Hello" out = Buf.getvalue () print "Captured", repr (out) Hint:see Stringio.stringio and Sys.stdout.Lets try to Understand how to capture output without context managers. Import sysfrom Stringio Import stringiooldstdout = Sys.stdoutbuf = Stringio () sys.stdout = bufprint "Hello" print "World" sys . StdOut = Oldstdoutprint "Captured", repr (Buf.getvalue ()) class Capture_output:def __iNit__ (self): Self.buf=stringio () def __enter__ (self): Self.oldstdout=sys.stdoutsys.stdout=self.bufreturn Self.bufdef __exit__ (self,type,exc,traceback): Sys.stdout=self.oldstdoutcapture_output () print "Hello"
Result
[' __class__ ', ' __delattr__ ', ' __doc__ ', ' __enter__ ', ' __exit__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init ' __ ', ' __iter__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __ Subclasshook__ ', ' close ', ' Closed ', ' encoding ', ' errors ', ' Fileno ', ' flush ', ' isatty ', ' mode ', ' name ', ' newlines ', ' Next ' , ' read ', ' Readinto ', ' readline ', ' readlines ', ' seek ', ' softspace ', ' Tell ', ' truncate ', ' write ', ' writelines ', ' xreadline S ']/users/macbook/proj/practisebefore with__init____enter__/private/tmp__exit__after with/Users/macbook/Proj/ Practisecaptured ' hello\nworld\n ' hello[finished in 0.1s]
16. Python Context Manager