0
# Convenience Functions
1
2
Simple function-based API for direct extended attribute operations without creating xattr objects. These functions are ideal for one-off operations and provide a straightforward interface for basic extended attribute manipulation.
3
4
## Capabilities
5
6
### Get Attribute
7
8
Retrieve the value of a single extended attribute from a file.
9
10
```python { .api }
11
def getxattr(f, attr, symlink=False):
12
"""
13
Get extended attribute value from file.
14
15
Parameters:
16
- f: str path, int file descriptor, or file-like object
17
- attr: str, attribute name
18
- symlink: bool, if True don't follow symbolic links
19
20
Returns:
21
bytes: attribute value
22
23
Raises:
24
IOError: filesystem error or attribute not found
25
"""
26
```
27
28
**Usage Examples:**
29
30
```python
31
import xattr
32
33
# Get attribute from file path
34
description = xattr.getxattr('/path/to/file', 'user.description')
35
print(description) # b'File description'
36
37
# Get attribute from symlink (not target)
38
link_attr = xattr.getxattr('/path/to/symlink', 'user.link_info', symlink=True)
39
40
# Get attribute using file descriptor
41
with open('/path/to/file', 'rb') as f:
42
title = xattr.getxattr(f.fileno(), 'user.title')
43
```
44
45
### Set Attribute
46
47
Set the value of a single extended attribute on a file.
48
49
```python { .api }
50
def setxattr(f, attr, value, options=0, symlink=False):
51
"""
52
Set extended attribute value on file.
53
54
Parameters:
55
- f: str path, int file descriptor, or file-like object
56
- attr: str, attribute name
57
- value: bytes, attribute value (must be bytes)
58
- options: int, operation flags (XATTR_CREATE, XATTR_REPLACE, etc.)
59
- symlink: bool, if True don't follow symbolic links
60
61
Raises:
62
IOError: filesystem error, permission denied, or flag constraints
63
TypeError: value is not bytes
64
"""
65
```
66
67
**Usage Examples:**
68
69
```python
70
import xattr
71
72
# Set basic attribute
73
xattr.setxattr('/path/to/file', 'user.description', b'My important file')
74
75
# Set with create flag (fail if exists)
76
xattr.setxattr('/path/to/file', 'user.id', b'12345', xattr.XATTR_CREATE)
77
78
# Set with replace flag (fail if doesn't exist)
79
xattr.setxattr('/path/to/file', 'user.version', b'2.0', xattr.XATTR_REPLACE)
80
81
# Set on symlink itself
82
xattr.setxattr('/path/to/symlink', 'user.link_type', b'shortcut', symlink=True)
83
84
# Set using file object
85
with open('/path/to/file', 'r+b') as f:
86
xattr.setxattr(f, 'user.modified_by', b'script')
87
```
88
89
### List Attributes
90
91
Retrieve a list of all extended attribute names for a file.
92
93
```python { .api }
94
def listxattr(f, symlink=False):
95
"""
96
List all extended attribute names for file.
97
98
Parameters:
99
- f: str path, int file descriptor, or file-like object
100
- symlink: bool, if True don't follow symbolic links
101
102
Returns:
103
tuple[str, ...]: attribute names with appropriate namespace prefixes
104
105
Raises:
106
IOError: filesystem error
107
"""
108
```
109
110
**Usage Examples:**
111
112
```python
113
import xattr
114
115
# List all attributes
116
attrs = xattr.listxattr('/path/to/file')
117
print(attrs) # ('user.description', 'user.title', 'user.version')
118
119
# List attributes on symlink itself
120
link_attrs = xattr.listxattr('/path/to/symlink', symlink=True)
121
122
# List using file descriptor
123
with open('/path/to/file', 'rb') as f:
124
attrs = xattr.listxattr(f.fileno())
125
for attr in attrs:
126
value = xattr.getxattr(f.fileno(), attr)
127
print(f"{attr}: {value}")
128
```
129
130
### Remove Attribute
131
132
Remove a single extended attribute from a file.
133
134
```python { .api }
135
def removexattr(f, attr, symlink=False):
136
"""
137
Remove extended attribute from file.
138
139
Parameters:
140
- f: str path, int file descriptor, or file-like object
141
- attr: str, attribute name to remove
142
- symlink: bool, if True don't follow symbolic links
143
144
Raises:
145
IOError: filesystem error or attribute not found
146
"""
147
```
148
149
**Usage Examples:**
150
151
```python
152
import xattr
153
154
# Remove attribute
155
xattr.removexattr('/path/to/file', 'user.old_description')
156
157
# Remove from symlink itself
158
xattr.removexattr('/path/to/symlink', 'user.temp_attr', symlink=True)
159
160
# Remove using file object
161
with open('/path/to/file', 'r+b') as f:
162
xattr.removexattr(f, 'user.cache_data')
163
164
# Remove all user attributes
165
attrs = xattr.listxattr('/path/to/file')
166
for attr in attrs:
167
if attr.startswith('user.'):
168
xattr.removexattr('/path/to/file', attr)
169
```
170
171
## Complete Workflow Example
172
173
Comprehensive example showing typical extended attribute operations using convenience functions.
174
175
```python
176
import xattr
177
178
# File path
179
filepath = '/path/to/document.txt'
180
181
# Set multiple attributes
182
metadata = {
183
'user.title': b'Important Document',
184
'user.author': b'John Doe',
185
'user.version': b'1.0',
186
'user.tags': b'work,important,draft'
187
}
188
189
for attr, value in metadata.items():
190
xattr.setxattr(filepath, attr, value)
191
192
# List and display all attributes
193
print("Extended attributes:")
194
for attr in xattr.listxattr(filepath):
195
value = xattr.getxattr(filepath, attr)
196
print(f" {attr}: {value.decode('utf-8', errors='replace')}")
197
198
# Update specific attribute
199
xattr.setxattr(filepath, 'user.version', b'1.1', xattr.XATTR_REPLACE)
200
201
# Check if attribute exists and get value
202
try:
203
description = xattr.getxattr(filepath, 'user.description')
204
print(f"Description: {description}")
205
except IOError:
206
print("No description set")
207
xattr.setxattr(filepath, 'user.description', b'Default description')
208
209
# Clean up - remove temporary attributes
210
temp_attrs = [attr for attr in xattr.listxattr(filepath)
211
if 'temp' in attr.lower()]
212
for attr in temp_attrs:
213
xattr.removexattr(filepath, attr)
214
```
215
216
## Error Handling
217
218
Convenience functions raise IOError/OSError for various filesystem conditions:
219
220
```python
221
import xattr
222
223
try:
224
# This will raise IOError if attribute doesn't exist
225
value = xattr.getxattr('/path/to/file', 'user.nonexistent')
226
except IOError as e:
227
if e.errno == 61: # ENODATA on Linux, ENOATTR on macOS
228
print("Attribute does not exist")
229
else:
230
print(f"Filesystem error: {e}")
231
232
try:
233
# This will raise TypeError if value is not bytes
234
xattr.setxattr('/path/to/file', 'user.test', 'not bytes')
235
except TypeError:
236
print("Values must be bytes")
237
xattr.setxattr('/path/to/file', 'user.test', b'correct bytes value')
238
```