返回顶部

python xattr库

因:

ceph 有一条设置 文件/目录 配额的命令ceph.quota.max_bytes,想在 Python 代码中调用它,最直接的方法是使用 popen/subprocess 等库直接执行这条命令,但如果频繁调用担心会影响系统性能,查阅资料发现 xattr库也可以实现且更加方便。

开始吧

首先需要安装xattr

pip3 install xattr

代码实现:

import xattr

file_path = "/mnt/shareDir/test1"
attribute_name = "ceph.quota.max_bytes"
attribute_value = "10086"

def set_attribute(file_path, attribute_name, attribute_value):
    xattr.setxattr(file_path, attribute_name, attribute_value)

def get_attribute(file_path, attribute_name):
    try:
        value = xattr.getxattr(file_path, attribute_name)
        return value
    except IOError:
        return None


set_attribute(file_path, attribute_name, attribute_value_bytes)

value = get_attribute(file_path, attribute_name)
print("The value of {0} is: {1}".format(attribute_name, value))
补充:

发现 python2 运行时正常,python3 运行时抛出错误

Traceback (most recent call last):
  File "set.py", line 17, in <module>
    set_attribute(file_path, attribute_name, "100098")
	...
	...
TypeError: Value must be bytes, str was passed.
	

python 3 中,setxattr 函数期望接收字节类型的值,可以使用 encode 方法将字符串转换为字节。

attribute_value_bytes = attribute_value.encode()
...
set_attribute(file_path, attribute_name, attribute_value_bytes)
value = get_attribute(file_path, attribute_name).decode()

成功解决!

posted @ 2023-12-20 10:34  十方央丶  阅读(207)  评论(0)    收藏  举报