本文整理汇总了Python中xattr.xattr函数的典型用法代码示例。如果您正苦于以下问题:Python xattr函数的具体用法?Python xattr怎么用?Python xattr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xattr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_attr
def test_attr(self):
x = xattr.xattr(self.tempfile)
self.assertEqual(x.keys(), [])
self.assertEqual(dict(x), {})
x['user.sopal'] = b'foo'
x['user.sop.foo'] = b'bar'
x[u'user.\N{SNOWMAN}'] = b'not a snowman'
del x
x = xattr.xattr(self.tempfile)
self.assertTrue('user.sopal' in x)
self.assertEqual(x['user.sopal'], b'foo')
self.assertTrue('user.sop.foo' in x)
self.assertEqual(x['user.sop.foo'], b'bar')
self.assertTrue(u'user.\N{SNOWMAN}' in x)
self.assertEqual(x[u'user.\N{SNOWMAN}'],
b'not a snowman')
del x[u'user.\N{SNOWMAN}']
del x['user.sop.foo']
del x
x = xattr.xattr(self.tempfile)
self.assertTrue('user.sop.foo' not in x)
示例2: remove_quarantine
def remove_quarantine(some_path):
'''Removes com.apple.quarantine from some_path'''
try:
if "com.apple.quarantine" in xattr.xattr(some_path).list():
xattr.xattr(some_path).remove("com.apple.quarantine")
except BaseException, err:
display.display_warning(
"Error removing com.apple.quarantine from %s: %s", some_path, err)
示例3: file_follow_durable
def file_follow_durable( path,
min_dump_interval=10,
xattr_name='user.collectd.logtail.pos', xattr_update=True,
**follow_kwz ):
'''Records log position into xattrs after reading line every
min_dump_interval seconds.
Checksum of the last line at the position
is also recorded (so line itself don't have to fit into xattr) to make sure
file wasn't truncated between last xattr dump and re-open.'''
from xattr import xattr
from io import open
from hashlib import sha1
from time import time
import struct
# Try to restore position
src = open(path, mode='rb')
src_xattr = xattr(src)
try:
if not xattr_name: raise KeyError
pos = src_xattr[xattr_name]
except KeyError: pos = None
if pos:
data_len = struct.calcsize('=I')
(pos,), chksum = struct.unpack('=I', pos[:data_len]), pos[data_len:]
(data_len,), chksum = struct.unpack('=I', chksum[:data_len]), chksum[data_len:]
try:
src.seek(pos - data_len)
if sha1(src.read(data_len)).digest() != chksum:
raise IOError('Last log line doesnt match checksum')
except (OSError, IOError) as err:
collectd.info('Failed to restore log position: {}'.format(err))
src.seek(0)
tailer = file_follow(src, yield_file=True, **follow_kwz)
# ...and keep it updated
pos_dump_ts_get = lambda ts=None: (ts or time()) + min_dump_interval
pos_dump_ts = pos_dump_ts_get()
while True:
line, src_chk = next(tailer)
if not line: pos_dump_ts = 0 # force-write xattr
ts = time()
if ts > pos_dump_ts:
if src is not src_chk:
src, src_xattr = src_chk, xattr(src_chk)
pos_new = src.tell()
if pos != pos_new:
pos = pos_new
if xattr_update:
src_xattr[xattr_name] =\
struct.pack('=I', pos)\
+ struct.pack('=I', len(line))\
+ sha1(line).digest()
pos_dump_ts = pos_dump_ts_get(ts)
if (yield line.decode('utf-8', 'replace')):
tailer.send(StopIteration)
break
示例4: testSymlinkAttrs
def testSymlinkAttrs(self):
symlinkPath = self.tempfilename + '.link'
os.symlink(self.tempfilename, symlinkPath)
try:
symlink = xattr.xattr(symlinkPath, options=xattr.XATTR_NOFOLLOW)
realfile = xattr.xattr(self.tempfilename)
symlink['user.islink'] = 'true'
self.assertEqual(dict(realfile), {})
self.assertEqual(symlink['user.islink'], 'true')
finally:
os.remove(symlinkPath)
示例5: assert_identical_directories
def assert_identical_directories(path1, path2):
"""
Verifies two directories have identical contents. Checks file type (via
the high byte of the mode), size, atime, and mtime, but does not check
other attributes like uid and gid, since they can be expected to change.
"""
seen = set([])
for file1 in os.listdir(path1):
seen.add(file1)
entry1 = os.path.join(path1, file1)
entry2 = os.path.join(path2, file1)
assert os.path.exists(entry2), "\"{f1}\" exists in \"{p1}\" but not \"{p2}\"".format(f1=file1, p1=path1, p2=path2)
# Extended attributes
xattr1 = xattr.xattr(entry1)
xattr2 = xattr.xattr(entry2)
assert set(xattr1.list()) == set(xattr2.list()), "list of extended attributes on \"{f1}\" ({l1}) differs from \"{f2}\" ({l2})".format(f1=entry1, l1=xattr1.list(), f2=entry2, l2=xattr2.list())
for attribute in xattr1.list():
assert xattr1.get(attribute) == xattr2.get(attribute), "extended attribute \"{a1}\" on \"{f1}\" doesn't match value from \"{f2}\"".format(a1=attribute, f1=entry1, f2=entry2)
# Why do it this way? We want to lstat() instead of stat(), so we can't use os.path.isdir() and friends
stat1 = os.lstat(entry1)
stat2 = os.lstat(entry2)
# Modes
mode1 = stat1.st_mode
mode2 = stat2.st_mode
if stat.S_ISREG(mode1):
assert stat.S_ISREG(mode2)
if stat.S_ISDIR(mode1):
assert stat.S_ISDIR(mode2)
if stat.S_ISLNK(mode1):
assert stat.S_ISLNK(mode2)
if stat.S_ISCHR(mode1):
assert stat.S_ISCHR(mode2)
if stat.S_ISBLK(mode1):
assert stat.S_ISBLK(mode2)
if stat.S_ISFIFO(mode1):
assert stat.S_ISFIFO(mode2)
if stat.S_ISSOCK(mode1):
assert stat.S_ISSOCK(mode2)
# Sizes and the like
assert stat1.st_size == stat2.st_size, "size mismatch for \"{e1}\" ({s1}) and \"{e2}\" ({s2})".format(e1=entry1, s1=stat1.st_size, e2=entry2, s2=stat2.st_size)
assert stat1.st_mtime == stat2.st_mtime, "mtime mismatch for \"{e1}\" and \"{e2}\"".format(e1=entry1, e2=entry2)
assert _md5_path(entry1) == _md5_path(entry2), "md5 hash mismatch for \"{e1}\" and \"{e2}\"".format(e1=entry1, e2=entry2)
if os.path.isdir(entry1):
assert_identical_directories(entry1, entry2)
for file2 in os.listdir(path2):
assert file2 in seen, "\"{f2}\" exists in \"{p2}\" but not \"{p1}\"".format(f2=file2, p1=path1, p2=path2)
示例6: test_symlink_attrs
def test_symlink_attrs(self):
# Solaris doesn't support extended attributes on symlinks
if sys.platform == 'sunos5':
return
symlinkPath = self.tempfilename + '.link'
os.symlink(self.tempfilename, symlinkPath)
try:
symlink = xattr.xattr(symlinkPath, options=xattr.XATTR_NOFOLLOW)
realfile = xattr.xattr(self.tempfilename)
symlink['user.islink'] = b'true'
self.assertEqual(dict(realfile), {})
self.assertEqual(symlink['user.islink'], b'true')
finally:
os.remove(symlinkPath)
示例7: process_COLOR
def process_COLOR(self, inpath, colorname):
try:
attrs = xattr.xattr(inpath)
if u'com.apple.FinderInfo' in attrs:
finder_attrs = attrs[u'com.apple.FinderInfo']
flags = struct.unpack(32*'B', finder_attrs)
else:
flags = 32 * (0,)
colorid = colorids[colorname]
if colorid == None:
colorid = 0
flag = flags[9] >> 1 & 7
flag &= 0xF1
flag |= (colorid << 1)
flags = list(flags)
flags[9] = flag
flags = tuple(flags)
finder_attrs = struct.pack(32*'B', *flags)
xattr.setxattr(inpath, u'com.apple.FinderInfo', finder_attrs)
self.send_response(200, 'OK')
self.end_headers()
except Exception as e:
print traceback.format_exc()
self.send_response(500, 'Internal Server Error')
self.end_headers()
示例8: promote
def promote(self, cf):
self.hierarchy += 1
store = os.path.join(cf.archive_store, self.job.name, self.id)
fname = "%s.1.%s" % (store, find_ext(self.type.name))
if os.path.exists(fname):
x = xattr.xattr(fname)
x['user.dardrive.hierarchy'] = str(self.hierarchy)
示例9: set_user_metadata
def set_user_metadata(path, user_metadata):
attrs = xattr.xattr(path)
try:
for key, value in user_metadata.iteritems():
attrs['user.%s' % key] = value
except IOError:
raise StorageException('object not modifiable or not found')
示例10: doquota
def doquota(self, ruri, size):
"""
We have to set the xattr WebDAV:{http:%2F%2Ftwistedmatrix.com%2Fxml_namespace%2Fdav%2Fprivate%2F}access-disabled
on the resource pointed to by the ruri. Strictly speaking only the server know how to map from a uri to a file
path, so we have to cheat!
"""
if self.manager.server_info.serverfilepath:
# __uids__ URI path is actually hashed on disk
segments = ruri[1:].split('/')
for ctr, segment in enumerate(segments):
if segment == "__uids__":
uid = segments[ctr + 1]
segments.insert(ctr + 1, uid[0:2])
segments.insert(ctr + 2, uid[2:4])
break
filepath = "/".join(segments)
filename = os.path.join(self.manager.server_info.serverfilepath, filepath)
if os.path.exists(filename):
attrs = xattr.xattr(filename)
if size is None:
del attrs["WebDAV:{http:%2F%2Ftwistedmatrix.com%2Fxml_namespace%2Fdav%2Fprivate%2F}quota-root"]
else:
attrs["WebDAV:{http:%2F%2Ftwistedmatrix.com%2Fxml_namespace%2Fdav%2Fprivate%2F}quota-root"] = \
"<?xml version='1.0' encoding='UTF-8'?>\n" + \
"<quota-root xmlns='http://twistedmatrix.com/xml_namespace/dav/private/'>" + \
str(size) + \
"</quota-root>"
return True
return False
示例11: test_symlink_attrs
def test_symlink_attrs(self):
symlinkPath = self.tempfilename + '.link'
os.symlink(self.tempfilename, symlinkPath)
try:
symlink = xattr.xattr(symlinkPath, options=xattr.XATTR_NOFOLLOW)
realfile = xattr.xattr(self.tempfilename)
try:
symlink['user.islink'] = b'true'
except IOError:
# Solaris, Linux don't support extended attributes on symlinks
raise unittest.SkipTest("XATTRs on symlink not allowed"
" on filesystem/platform")
self.assertEqual(dict(realfile), {})
self.assertEqual(symlink['user.islink'], b'true')
finally:
os.remove(symlinkPath)
示例12: read_tags
def read_tags(fname):
"""Return a list of Tags of the xatag xattr fields in fname."""
attributes = xattr.xattr(fname)
# no sense in reading the value if the key isn't going to be chosen
return [tag.Tag(xattr_to_xatag_key(k), val)
for k in attributes if is_xatag_xattr_key(k)
for val in xattr_value_to_list(attributes[k])]
示例13: upload
def upload(source, resource_id=None, **kwargs):
"""Uploads a file to a datastore table"""
verbose = not kwargs['quiet']
resource_id = resource_id or p.splitext(p.basename(source))[0]
if '.' in resource_id:
resource_id = resource_id.split('.')[0]
ckan_kwargs = {k: v for k, v in kwargs.items() if k in api.CKAN_KEYS}
if verbose:
print(
'Uploading %s to datastore resource %s...' % (source, resource_id))
# read encoding from extended attributes
x = xattr(source)
try:
kwargs['encoding'] = x.get('com.ckanny.encoding')
except IOError:
pass
if verbose and kwargs['encoding']:
print('Using encoding %s' % kwargs['encoding'])
ckan = CKAN(**ckan_kwargs)
if ckan.update_datastore(resource_id, source, **kwargs):
print('Success! Resource %s uploaded.' % resource_id)
else:
sys.exit('ERROR: resource %s not uploaded.' % resource_id)
示例14: fetch
def fetch(resource_id, **kwargs):
"""Downloads a filestore resource"""
verbose = not kwargs['quiet']
filepath = kwargs['destination']
name_from_id = kwargs.get('name_from_id')
chunksize = kwargs.get('chunksize_bytes')
ckan_kwargs = {k: v for k, v in kwargs.items() if k in api.CKAN_KEYS}
ckan = CKAN(**ckan_kwargs)
try:
r = ckan.fetch_resource(resource_id)
except api.NotAuthorized as err:
sys.exit('ERROR: %s\n' % str(err))
else:
fkwargs = {
'headers': r.headers,
'name_from_id': name_from_id,
'resource_id': resource_id}
filepath = tup.make_filepath(filepath, **fkwargs)
tio.write(filepath, r.iter_content, chunksize=chunksize)
# save encoding to extended attributes
x = xattr(filepath)
if verbose and r.encoding:
print('saving encoding %s to extended attributes' % r.encoding)
if r.encoding:
x['com.ckanny.encoding'] = r.encoding
print(filepath)
示例15: __init__
def __init__(self, mp):
self.context = carvpath.Context(longpathmap.LongPathMap())
self.mountpoint = mp
ctlpath = self.mountpoint + "/mattockfs.ctl"
if not os.path.isfile(ctlpath):
raise RuntimeError("File-system not mounted at "+mp)
self.main_ctl = xattr.xattr(ctlpath)