In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to master the technology of monitoring file system in Python". The content of this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to master the technology of monitoring file system in Python".
Watch dog, the watchdog
By reading this article, you will learn how to detect changes to existing files in your Python application. We will use a well-maintained module called watchdog (watchdog). Based on official documentation, watchdog is a Python API library and shell utility for monitoring file system events.
It supports both Python 2.7 and 3.4 +. However, for older versions, it is recommended that you use watchdog < 0.10.0. In this tutorial, I will only introduce the Python API library. Let's move on to the next section and start installing the necessary modules.
Set up
Setup is fairly simple and straightforward for pip installation. It is strongly recommended that you set up a virtual environment before continuing. There are two ways.
Installed in PyPI
Run the following command in the terminal.
Pip install watchdog
It will install the latest version of PyPI (0.10.2 at the time of this writing).
Install from the code base
In addition, you can clone the repository in your local folder and install it normally. First, let's clone it using the following command.
Git clone-recursive git://github.com/gorakhargosh/watchdog.git
Use the following command to change the working directory. Make sure it contains a file named setup.py in the working directory.
Cd watchdog
Run the following command to install it.
Pip install-e.
One of the main advantages of cloning it directly from the repository is that you can get the latest version with additional features.
You can run the following command in the terminal to verify that the installation was successful.
Pip show watchdog
Let's move on to the next section and start writing Python code.
Realize
The main building blocks of watchdog are based on the following classes:
Observer
Event handler
So, the implementation is as simple as this:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Create an instance of watchdog.observers. Observer thread class.
Use your own implementation to define subclasses of event handlers and create instances from them.
The scheduling function is called through the observer instance of the attached event handler. It accepts some other input parameters, such as the path of the directory to be monitored.
Start the observer thread and wait for it to generate events that trigger the code in the event handler.
Event handler
There are four types of event handlers available in the current module:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
FileSystemEventHandler- can override the basic file system event handler for the methods in it.
PatternMatchingEventHandler-- matches the given pattern with the file path associated with the event that is happening.
RegexMatchingEventHandler-matches the given regular expression and the file path associated with the event.
LoggingEventHandler- records all events captured.
The rest of the classes inherit from FileSystemEventHandler, which provides the following functions for us to rewrite.
On_any_event-captures all event handlers.
On_created-called when a file or directory is created.
On_deleted-called when a file or directory is deleted.
On_modified-called when a file or directory is modified.
On_moved-called when a file or directory is moved or renamed.
Import
Create a new Python file and add the following import declaration. I named it test.py.
From watchdog.observers import Observer from watchdog.events import FileSystemEventHandler
Subclasses of FileSystemEventHandler
Create a new class that inherits from FileSystemEventHandler and override these functions accordingly according to the use case. I'll name it MyHandler, but you can name it whatever you want.
Class MyHandler (FileSystemEventHandler): def on_any_event (self, event): print (event.event_type, event.src_path) def on_created (self, event): print ("on_created", event.src_path) def on_deleted (self, event): print ("on_deleted", event.src_path) def on_modified (self, event): print ("on_modified" Event.src_path) def on_moved (self, event): print ("on_moved", event.src_path)
Replace the print statement with the implemented logic. For each function, it has an input parameter named event, which contains the following variables:
The event type in the form of an event_type- string. The default is no.
Is_directory-if the event is triggered for the directory, True; otherwise error.
The source path of the file system object that src_path- triggered this event.
The most useful parameter is src_path, where you can use it to determine which file has been modified and then run the appropriate logic.
If (event.src_path = ". / path/file.txt"): print ("Execute your logic here!")
Observers and events
Once you have created a subclass, you can safely create an instance of it with the observer class. Assign the path you selected to the monitoring process. I will examine a newly created folder called json. You can modify it according to your preferences.
You can also set recursive recursive parameters, but it is strongly recommended that you pre-define the hierarchy and set it to false to prevent insufficient permissions or inability to access subfolders.
Calling start runs the thread, and an event is generated when you make changes in the appropriate path.
Event_handler = MyHandler () observer = Observer () observer.schedule (event_handler, path='./json/', recursive=False) observer.start ()
test
To test it, you must implement a running loop to prevent it from exiting. When exiting a KeyboardInterrupt exception, the stop function is called to clean up the resource.
While True: try: pass except KeyboardInterrupt: observer.stop ()
Save the Python file and run it in the terminal. Modify the name according to the name you set.
Python test.py
You can easily test it by creating a new document, modifying its contents, and removing it from the directory.
Thank you for your reading, the above is the content of "how to master the technology of monitoring file system in Python". After the study of this article, I believe you have a deeper understanding of how to master the technology of monitoring file system in Python. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.