[linux]: Obtain system memory and memory cleanup operation (python)

1. os.statvf() function introduction

The os.statvfs() method is used to return information about the file system of the file containing the file descriptor fd.
Syntax
The syntax of the statvfs() method is as follows:

os.statvfs([path])

Parameters
path – file path.

Return value
Returned structure:

f_bsize: 文件系统块大小
f_frsize: 分栈大小
f_blocks: 文件系统数据块总数
f_bfree: 可用块数
f_bavail:非超级用户可获取的块数
f_files: 文件结点总数
f_ffree: 可用文件结点数
f_favail: 非超级用户的可用文件结点数
f_fsid: 文件系统标识 ID
f_flag: 挂载标记
f_namemax: 最大文件长度

Explanation: According to the return value, we can use the two parameters f_bavail and f_frsize to obtain the remaining free space in the system:

2. Acquisition of remaining system memory:

可以使用以下代码来实现:

```python
import os

# 获取当前目录所在文件系统的信息
fs_info = os.statvfs('.')

# 计算可用空间大小(以字节为单位)
available_space = fs_info.f_frsize * fs_info.f_bavail

# 将可用空间转换为以M为单位
available_space_in_mb = available_space / (1024.0 ** 2)

print(f"可用空间为:{
      
      available_space_in_mb:.2f}M")

Run the above code to output the available space (in M) of the file system where the current directory is located on the terminal. Note that when executing this code, you need to ensure that the file system where the current directory is located is mounted and available

3. File Cleanup

When the remaining memory in the system is less than 1G, directly clear the corresponding "jpg file" in the specified folder

import os

def clear_img_folder():
    img_folder = '/home/pi/Desktop/test_init1/err' # 替换为实际的img文件夹路径
    total, used, free = os.statvfs(img_folder)[:3]
    available_space = (free * total) / 1024 / 1024 # 计算剩余可用空间,单位为MB
    print("Available space is:",os.statvfs(img_folder)[:3])
    if available_space < 1000: # 判断剩余空间是否小于1G
        print('Available space is less than 1G. Cleaning img folder...')
        for file_name in os.listdir(img_folder):
            if file_name.endswith('.jpg'):
                os.remove(os.path.join(img_folder, file_name))
        print('Img folder is cleaned.')
    else:
        print('Available space is enough. No need to clean.')

if __name__ == '__main__':
    clear_img_folder()

Guess you like

Origin blog.csdn.net/weixin_44322778/article/details/130707471