[Diaoye learns programming] MicroPython manual built-in module stat

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small, and the memory usage is small, which is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

The application scenarios of MicroPython include:
1. Quickly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Pay attention to the following when using MicroPython:
1. The memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here
MicroPython's built-in module stat provides some constants and functions for handling file status. Its main features, application scenarios, and matters needing attention are as follows:

Main features: The stat module defines some constants, such as stat.S_IFDIR, stat.S_IFREG, etc., to indicate the type of file. The stat module also defines some functions, such as stat.stat(path), stat.fstat(fd), etc., for obtaining file status information. The status information of a file is a tuple, including the file size, modification time, permissions and other attributes. The stat module also provides some auxiliary functions, such as stat.S_ISDIR(mode), stat.S_ISREG(mode), etc., for determining the type of file.

Application scenario: The stat module can be used to obtain and process file status information in the file system. For example, you can use the stat module to determine whether a path is a directory or a file, or to obtain the size or modification time of a file, etc.

Things to note: Before using the stat module, you need to import the module and use the import stat statement. Before using the functions of the stat module, you need to ensure that the file or path exists. Otherwise, an exception is thrown. Additionally, the stat module may have different implementations and support on different platforms. Therefore, when using the stat module, it is best to first check the platform's features and limitations1.

The following are several practical application examples of MicroPython's built-in module stat:

Case 1: Get the size and modification time of a file named 'test.txt' on the MicroPython board. code show as below:

import os
import stat
import time

# 定义要获取状态信息的文件路径
path = 'test.txt'

# 获取文件的状态信息
st = os.stat(path)

# 获取文件的大小(字节)
size = st[6]

# 获取文件的修改时间(秒)
mtime = st[8]

# 格式化修改时间为字符串
mtime_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime))

# 打印文件的大小和修改时间
print('The size of', path, 'is', size, 'bytes')
print('The last modified time of', path, 'is', mtime_str)

Case 2: Determine whether a path named 'temp' is a directory or a file on the MicroPython board. code show as below:

import os
import stat

# 定义要判断类型的路径
path = 'temp'

# 获取路径的状态信息
st = os.stat(path)

# 获取路径的类型(mode)
mode = st[0]

# 判断路径是否是一个目录
if stat.S_ISDIR(mode):
    print(path, 'is a directory')
# 判断路径是否是一个文件
elif stat.S_ISREG(mode):
    print(path, 'is a file')
# 其他情况
else:
    print(path, 'is neither a directory nor a file')

Case 3: Modify the permissions of a file named 'image.jpg' on the MicroPython board so that it can only be read and written by the owner. code show as below:

import os
import stat

# 定义要修改权限的文件路径
path = 'image.jpg'

# 获取文件的状态信息
st = os.stat(path)

# 获取文件的当前权限(mode)
mode = st[0]

# 计算新的权限(只保留所有者读写位)
new_mode = mode & (stat.S_IRUSR | stat.S_IWUSR)

# 修改文件的权限
os.chmod(path, new_mode)

# 打印修改后的权限
print('The new mode of', path, 'is', oct(new_mode))

Case 4: Get file information:

import os
import stat

# 定义文件路径
file_path = "/home/pi/documents/file.txt"

# 获取文件信息
file_stat = os.stat(file_path)

# 打印文件信息
print("文件大小:", file_stat.st_size, "字节")
print("最后修改时间:", file_stat.st_mtime)
print("最后访问时间:", file_stat.st_atime)
print("文件权限:", stat.filemode(file_stat.st_mode))

In this example, we use the stat function of the os module to obtain information about the specified file. We define the file path and then use the os.stat function to obtain the stat object of the file. By accessing the properties of the stat object, we can get the file's size in bytes, last modification time, last access time, and file permissions. We use the stat.filemode function to convert the permission values ​​into readable form and print out the file information.

Case 5: Check if the file is a directory:

import os

# 定义路径
path = "/home/pi/documents"

# 检查路径是否为目录
if os.path.isdir(path):
    print("该路径是一个目录")
else:
    print("该路径不是一个目录")

In this example, we use the isdir function of the os module to check whether the specified path is a directory. We define the path and then check the path using the os.path.isdir function. If the path is a directory, we print the message "The path is a directory". If the path is not a directory, we print the message "The path is not a directory".

Case 6: Check whether the file is an ordinary file:

import os

# 定义路径
path = "/home/pi/documents/file.txt"

# 检查路径是否为普通文件
if os.path.isfile(path):
    print("该路径是一个普通文件")
else:
    print("该路径不是一个普通文件")

In this example, we use the isfile function of the os module to check whether the specified path is an ordinary file. We define the path and then check the path using the os.path.isfile function. If the path is a normal file, we print the message "The path is a normal file". If the path is not an ordinary file, we print out the message "The path is not an ordinary file".

Case 7: Get file size, creation time and modification time

import uos

# 获取文件 "data.txt" 的状态信息
file_stat = uos.stat("data.txt")

# 提取文件大小
file_size = file_stat[6]
print("文件大小:", file_size, "字节")

# 提取文件的创建时间和修改时间
create_time = file_stat[8]
modify_time = file_stat[9]
print("创建时间:", create_time)
print("修改时间:", modify_time)

This example uses the uos.stat() function to obtain status information for the file "data.txt" and extracts the file's size, creation time, and modification time from the returned tuple.

Case 8: Check if the file is a directory

import uos

# 检查文件 "data" 是否为目录
file_stat = uos.stat("data")
is_directory = file_stat[0] & 0x4000  # 目录的标志位为 0x4000

if is_directory:
    print("文件是一个目录")
else:
    print("文件不是一个目录")

In this example, we use the uos.stat() function to obtain the status information of the file "data" and determine whether the file is a directory by checking the returned flag bit.

Case 9: Obtaining access to files

import uos

# 获取文件 "script.py" 的访问权限
file_stat = uos.stat("script.py")
access_permissions = file_stat[0] & 0o777  # 通过掩码提取访问权限

print("访问权限:", oct(access_permissions))

In this example, we use the uos.stat() function to obtain the status information of the file "script.py" and extract the file's access permissions through masking. The access rights returned are an octal value, which can be converted to an octal representation using the oct() function.

These cases demonstrate the practical application of the uos.stat() function, including obtaining the file size, creation time and modification time, checking whether the file is a directory, and obtaining file access permissions. By using the stat function, you can easily obtain the status information of the file on the MicroPython device and perform further processing and judgment as needed. Please note that when using the stat function, please ensure that you have sufficient permissions and reasonable path settings, and make appropriate adjustments and processing according to actual needs.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132787281