平时的笔记02:处理fnmatch模块

# Copyright 2006 Joe Wreschnig
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# $Id: _util.py 4218 2007-12-02 06:11:20Z piman $

"""Utility classes for Mutagen.

You should not rely on the interfaces here being stable. They are
intended for internal use in Mutagen only.
"""

import struct

from fnmatch import fnmatchcase

class DictMixin(object):
"""Implement the dict API using keys() and __*item__ methods.

Similar to UserDict.DictMixin, this takes a class that defines
__getitem__, __setitem__, __delitem__, and keys(), and turns it
into a full dict-like object.

UserDict.DictMixin is not suitable for this purpose because it‘s
an old-style class.

This class is not optimized for very large dictionaries; many
functions have linear memory requirements. I recommend you
override some of these functions if speed is required.
"""

def __iter__(self):
return iter(self.keys())

def has_key(self, key):
try: self[key]
except KeyError: return False
else: return True
__contains__ = has_key

iterkeys = lambda self: iter(self.keys())

def values(self):
return map(self.__getitem__, self.keys())
itervalues = lambda self: iter(self.values())

def items(self):
return zip(self.keys(), self.values())
iteritems = lambda s: iter(s.items())

def clear(self):
map(self.__delitem__, self.keys())

def pop(self, key, *args):
if len(args) > 1:
raise TypeError("pop takes at most two arguments")
try: value = self[key]
except KeyError:
if args: return args[0]
else: raise
del(self[key])
return value

def popitem(self):
try:
key = self.keys()[0]
return key, self.pop(key)
except IndexError: raise KeyError("dictionary is empty")

def update(self, other=None, **kwargs):
if other is None:
self.update(kwargs)
other = {}

try: map(self.__setitem__, other.keys(), other.values())
except AttributeError:
for key, value in other:
self[key] = value

def setdefault(self, key, default=None):
try: return self[key]
except KeyError:
self[key] = default
return default

def get(self, key, default=None):
try: return self[key]
except KeyError: return default

def __repr__(self):
return repr(dict(self.items()))

def __cmp__(self, other):
if other is None: return 1
else: return cmp(dict(self.items()), other)

def __len__(self):
return len(self.keys())

class DictProxy(DictMixin):
def __init__(self, *args, **kwargs):
self.__dict = {}
super(DictProxy, self).__init__(*args, **kwargs)

def __getitem__(self, key):
return self.__dict[key]

def __setitem__(self, key, value):
self.__dict[key] = value

def __delitem__(self, key):
del(self.__dict[key])

def keys(self):
return self.__dict.keys()

class cdata(object):
"""C character buffer to Python numeric type conversions."""

from struct import error

short_le = staticmethod(lambda data: struct.unpack(‘<h‘, data)[0])
ushort_le = staticmethod(lambda data: struct.unpack(‘<H‘, data)[0])

short_be = staticmethod(lambda data: struct.unpack(‘>h‘, data)[0])
ushort_be = staticmethod(lambda data: struct.unpack(‘>H‘, data)[0])

int_le = staticmethod(lambda data: struct.unpack(‘<i‘, data)[0])
uint_le = staticmethod(lambda data: struct.unpack(‘<I‘, data)[0])

int_be = staticmethod(lambda data: struct.unpack(‘>i‘, data)[0])
uint_be = staticmethod(lambda data: struct.unpack(‘>I‘, data)[0])

longlong_le = staticmethod(lambda data: struct.unpack(‘<q‘, data)[0])
ulonglong_le = staticmethod(lambda data: struct.unpack(‘<Q‘, data)[0])

longlong_be = staticmethod(lambda data: struct.unpack(‘>q‘, data)[0])
ulonglong_be = staticmethod(lambda data: struct.unpack(‘>Q‘, data)[0])

to_short_le = staticmethod(lambda data: struct.pack(‘<h‘, data))
to_ushort_le = staticmethod(lambda data: struct.pack(‘<H‘, data))

to_short_be = staticmethod(lambda data: struct.pack(‘>h‘, data))
to_ushort_be = staticmethod(lambda data: struct.pack(‘>H‘, data))

to_int_le = staticmethod(lambda data: struct.pack(‘<i‘, data))
to_uint_le = staticmethod(lambda data: struct.pack(‘<I‘, data))

to_int_be = staticmethod(lambda data: struct.pack(‘>i‘, data))
to_uint_be = staticmethod(lambda data: struct.pack(‘>I‘, data))

to_longlong_le = staticmethod(lambda data: struct.pack(‘<q‘, data))
to_ulonglong_le = staticmethod(lambda data: struct.pack(‘<Q‘, data))

to_longlong_be = staticmethod(lambda data: struct.pack(‘>q‘, data))
to_ulonglong_be = staticmethod(lambda data: struct.pack(‘>Q‘, data))

bitswap = ‘‘.join([chr(sum([((val >> i) & 1) << (7-i) for i in range(8)]))
for val in range(256)])
del(i)
del(val)

test_bit = staticmethod(lambda value, n: bool((value >> n) & 1))

def lock(fileobj):
"""Lock a file object ‘safely‘.

That means a failure to lock because the platform doesn‘t
support fcntl or filesystem locks is not considered a
failure. This call does block.

Returns whether or not the lock was successful, or
raises an exception in more extreme circumstances (full
lock table, invalid file).
"""
try: import fcntl
except ImportError:
return False
else:
try: fcntl.lockf(fileobj, fcntl.LOCK_EX)
except IOError:
# FIXME: There‘s possibly a lot of complicated
# logic that needs to go here in case the IOError
# is EACCES or EAGAIN.
return False
else:
return True

def unlock(fileobj):
"""Unlock a file object.

Don‘t call this on a file object unless a call to lock()
returned true.
"""
# If this fails there‘s a mismatched lock/unlock pair,
# so we definitely don‘t want to ignore errors.
import fcntl
fcntl.lockf(fileobj, fcntl.LOCK_UN)

def insert_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Insert size bytes of empty space starting at offset.

fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
assert 0 < size
assert 0 <= offset
locked = False
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset
fobj.write(‘\x00‘ * size)
fobj.flush()
try:
try:
import mmap
map = mmap.mmap(fobj.fileno(), filesize + size)
try: map.move(offset + size, offset, movesize)
finally: map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.truncate(filesize)

fobj.seek(0, 2)
padsize = size
# Don‘t generate an enormous string if we need to pad
# the file out several megs.
while padsize:
addsize = min(BUFFER_SIZE, padsize)
fobj.write("\x00" * addsize)
padsize -= addsize

fobj.seek(filesize, 0)
while movesize:
# At the start of this loop, fobj is pointing at the end
# of the data we need to move, which is of movesize length.
thismove = min(BUFFER_SIZE, movesize)
# Seek back however much we‘re going to read this frame.
fobj.seek(-thismove, 1)
nextpos = fobj.tell()
# Read it, so we‘re back at the end.
data = fobj.read(thismove)
# Seek back to where we need to write it.
fobj.seek(-thismove + size, 1)
# Write it.
fobj.write(data)
# And seek back to the end of the unmoved data.
fobj.seek(nextpos)
movesize -= thismove

fobj.flush()
finally:
if locked:
unlock(fobj)

def delete_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Delete size bytes of empty space starting at offset.

fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
locked = False
assert 0 < size
assert 0 <= offset
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset - size
assert 0 <= movesize
try:
if movesize > 0:
fobj.flush()
try:
import mmap
map = mmap.mmap(fobj.fileno(), filesize)
try: map.move(offset, offset + size, movesize)
finally: map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
while buf:
fobj.seek(offset)
fobj.write(buf)
offset += len(buf)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
fobj.truncate(filesize - size)
fobj.flush()
finally:
if locked:
unlock(fobj)

def utf8(data):
"""Convert a basestring to a valid UTF-8 str."""
if isinstance(data, str):
return data.decode("utf-8", "replace").encode("utf-8")
elif isinstance(data, unicode):
return data.encode("utf-8")
else: raise TypeError("only unicode/str types can be converted to UTF-8")

def dict_match(d, key, default=None):
try:
return d[key]
except KeyError:
for pattern, value in d.iteritems():
if fnmatchcase(key, pattern):
return value
return default

平时的笔记02:处理fnmatch模块

时间: 2024-10-05 06:05:27

平时的笔记02:处理fnmatch模块的相关文章

平时的笔记02:处理mp3

#! /usr/bin/env python # # mutagen aims to be an all purpose media tagging library # Copyright (C) 2005  Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Publi

平时的笔记02:硬件信息

# -*- coding: utf-8 -*- from ctypes import * import time class MEMORYSTATUS(Structure): while 1: _fields_ = [('dwLength', c_int), ('dwMemoryLoad', c_int), ('dwTotalPhys', c_int), ('dwAvailPhys', c_int), ('dwTotalPageFile', c_int), ('dwAvailPageFile',

《构建之法》阅读笔记02

<架构之美>阅读笔记02 今天,我读了<架构之美>第三.四章,第三章主要讲伸缩性架构设计,书中说设计系统架构时,要确保系统在伸缩时的弹性,根据书中的介绍我对系统伸缩性的理解是每个网站在不同时期都会有不同的访问量,有时会很多,有时会较少,当较多的人访问你的系统时,你可能需要数量较多的设备来满足用户与系统的交互,但当访问的用户越来越少时,系统伸缩性如果不够好,很多设备就会被浪费,不能够与系统分离,这对于软件开发者是不可取的.Darkstar项目就是由Sun公司实验室承担的一个将在架构的

张高兴的 Windows 10 IoT 开发笔记:RTC 时钟模块 DS3231

原文:张高兴的 Windows 10 IoT 开发笔记:RTC 时钟模块 DS3231 GitHub:https://github.com/ZhangGaoxing/windows-iot-demo/tree/master/DS3231 注意:不包含闹钟设置

【OpenGL 学习笔记02】宽点画线

我们要知道,有三种绘图操作是最基本的:清除窗口,绘制几何图形,绘制光栅化对象. 光栅化对象后面再解释. 1.清除窗口 比如我们可以同时清除颜色缓冲区和深度缓冲区 glClearColor (0.0, 0.0, 0.0, 0.0);//指定颜色缓冲区清除为黑色 glClearDepth(1.0);//指定深度缓冲区的清除值为1.0 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//指定要清除的缓冲区并清除 2.绘制几何图形 先要设置绘制颜色,

SWIFT学习笔记02

1.//下面的这些浮点字面量都等于十进制的12.1875: let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0//==12+3*(1/16) 2.//类型别名,用typealias关键字来定义类型别名 typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min 3.//元组 let ht

Blender学习笔记 | 02 | 操作

Shift 点击不同图层 同时显示多图层物件 z 切换 Solid / Wireframe 视图模式 点选物件后M 移动到图层选项 Ctrl + 鼠标左键拖动 自由全选物件 B 方形区域圈选物件 Tab Object / Edit Mode 切换 T 开 / 关 侧栏 Ctrl + Tab 编辑状态下切换编辑对象 E Extrude Region 推挤区域.以发现为轴线. X 删除物件菜单 Blender学习笔记 | 02 | 操作,布布扣,bubuko.com

《用户故事与敏捷开发》阅读笔记02

 <用户故事与敏捷开发>阅读笔记02       这周读了<用户故事与敏捷开发>的第四至七章,第四章讲述的是如何搜集故事,也就是如何正确的去找到用户需求.作者明确指出"引用"和"捕捉"是不合用的.所谓"引用"和"捕捉",我想是通过用户对功能的表述,开发人员从中获取需求信息吧.如果是这种方法来获取需求,正如作者所说,用户不会知道所有的需求,所以只靠着这方法是远远不够的.对于故事编写的数量以及程度,作者认为

mongodb 学习笔记 02 -- CURD操作

mongodb 学习笔记 02 – CURD操作 CURD代表创建(Create).更新(Update).读取(Read)和删除(Delete)操作 创建库 直接 use 库名 然后创建collection 就可以创建库 创建collecion db.createCollection("collectionName") 隐式创建collection db.collectionName.insert({xxxxxx}) 删除collection db.collectionName.dro