In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of how to use Python with and context management tools, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Python with and context management tools. Let's take a look.
Preface
If you are in the habit of reading source code, you may see that some good code often shows statements with the keyword "with". What scenarios are they usually used in? Today I'm going to talk about with and context manager.
For system resources such as files, database connections, and socket, one of the things that an application must do after opening these resources and performing business logic is to close (disconnect) the resource.
For example, the Python program opens a file, writes to it, and closes the file after it has been written. Otherwise, what will happen? In extreme cases, there will be a "Too many open files" error because the maximum number of files that the system allows you to open is limited.
Similarly, for databases, "Can not connect to MySQL server Too many connections" may occur if there are too many connections to close in time, because database connections are a very expensive resource and cannot be created indefinitely.
Let's see how to close a file correctly.
Ordinary version
Def test1 ():
F = open ("output.txt", "w")
F.write ("Zen of python")
F.close ()
There is a potential problem with this. If an exception occurs during the call to write and the subsequent code cannot continue to execute, the close method cannot be called normally, so the resources will always be occupied by the program and cannot be released. So how do you improve the code?
Advanced edition
Def test2 ():
F = open ("output.txt", "w")
Try:
F.write ("Zen of python")
Except IOError:
Print ("oops error")
Finally:
F.close ()
The improved version of the program is to try capture the code where an exception may occur, using the try/finally statement, which means that if there is an exception in the try code block, the subsequent code will no longer execute and jump directly to the except code block. In any case, the code for the finally block will eventually be executed. Therefore, as long as you put the close in the finally code, the file is bound to close.
Advanced edition
Def test3 ():
With open ("output.txt", "w") as f:
F.write ("Zen of Python")
A more concise and elegant way is to use the with keyword. The return value of the open method is assigned to the variable f, and the f.close () method is automatically called when you leave the with code block, and with serves the same purpose as using the try/finally statement. So what is the principle of its implementation? Before we talk about the principle of with, we should involve another concept, that is, the context manager (Context Manager).
Context Manager
Any object that implements the _ _ enter__ () and _ _ exit__ () methods can be called a context manager, and the context manager object can use the with keyword. Obviously, the file (file) object also implements the context manager.
So how does the file object implement these two methods? We can simulate and implement a file class of our own, which implements the _ _ enter__ () and _ _ exit__ () methods.
Class File ():
Def _ _ init__ (self, filename, mode):
Self.filename = filename
Self.mode = mode
Def _ enter__ (self):
Print ("entering")
Self.f = open (self.filename, self.mode)
Return self.f
Def _ _ exit__ (self, * args):
Print ("will exit")
Self.f.close ()
The _ _ enter__ () method returns the resource object, which is the file object you are about to open, and the _ _ exit__ () method handles some cleanup work.
Because the File class implements the context manager, you can now use the with statement.
With File ('out.txt', 'w') as f:
Print ("writing")
F.write ('hello, python')
In this way, you do not have to explicitly call the close method, which is called automatically by the system, and the close method will be called even if an exception is encountered in the middle.
Contextlib
Python also provides a contextmanager decorator, which further simplifies the implementation of the context manager. The function is divided into two parts through yield, with statements before yield executed in the _ _ enter__ method and statements after yield executed in the _ _ exit__ method. The value immediately after yield is the return value of the function.
From contextlib import contextmanager
@ contextmanager
Def my_open (path, mode):
F = open (path, mode)
Yield f
F.close ()
Call:
With my_open ('out.txt', 'w') as f:
F.write ("hello, the simplest context manager")
This is the end of the article on "how to use Python with and context Management tools". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use Python with and context management tools". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.