def strFile(p, f, caseSensitive=True):
"""Find whether string p occurs in a read()able object f
@rtype: C{bool}
"""
buf = ""
buf_len = max(len(p), 2**2**2**2)
if not caseSensitive:
p = p.lower()
while 1:
r = f.read(buf_len-len(p))
if not caseSensitive:
r = r.lower()
bytes_read = len(r)
if bytes_read == 0:
return False
l = len(buf)+bytes_read-buf_len
if l <= 0:
buf = buf + r
else:
buf = buf[l:] + r
if buf.find(p) != -1:
return True
python类find()的实例源码
def stripEscapes(self, string):
"""
Remove all ANSI color escapes from the given string.
"""
result = ''
show = 1
i = 0
L = len(string)
while i < L:
if show == 0 and string[i] in _sets:
show = 1
elif show:
n = string.find('\x1B', i)
if n == -1:
return result + string[i:]
else:
result = result + string[i:n]
i = n
show = 0
i = i + 1
return result
def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = string.find(sys.version, prefix)
if i == -1:
return 6
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
# I don't think paths are affected by minor version in version 6
if majorVersion == 6:
minorVersion = 0
if majorVersion >= 6:
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None
def find_library_file (self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
if debug:
try_names = [lib + "_d", lib]
else:
try_names = [lib]
for dir in dirs:
for name in try_names:
libfile = os.path.join(dir, self.library_filename (name))
if os.path.exists(libfile):
return libfile
else:
# Oops, didn't find it in *any* of 'dirs'
return None
# find_library_file ()
# Helper methods for using the MSVC registry settings
def find_exe(self, exe):
"""Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the original program name, 'exe'.
"""
for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
# didn't find it; try existing path
for p in string.split(os.environ['Path'],';'):
fn = os.path.join(os.path.abspath(p),exe)
if os.path.isfile(fn):
return fn
return exe
def get_msvcr():
"""Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later.
"""
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
if msc_ver == '1300':
# MSVC 7.0
return ['msvcr70']
elif msc_ver == '1310':
# MSVC 7.1
return ['msvcr71']
elif msc_ver == '1400':
# VS2005 / MSVC 8.0
return ['msvcr80']
elif msc_ver == '1500':
# VS2008 / MSVC 9.0
return ['msvcr90']
else:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
def __getfilesystemencoding():
'''
Note: there's a copy of this method in _pydev_filesystem_encoding.py
'''
try:
ret = sys.getfilesystemencoding()
if not ret:
raise RuntimeError('Unable to get encoding.')
return ret
except:
try:
# Handle Jython
from java.lang import System # @UnresolvedImport
env = System.getProperty("os.name").lower()
if env.find('win') != -1:
return 'ISO-8859-1' # mbcs does not work on Jython, so, use a (hopefully) suitable replacement
return 'utf-8'
except:
pass
# Only available from 2.3 onwards.
if sys.platform == 'win32':
return 'mbcs'
return 'utf-8'
def getControllers():
"""
Query the controllers available, and return this in a list.
Returns: List with available 3ware controllers (list).
"""
T = TRACE()
cmd = "sudo /usr/local/sbin/tw_cli info"
stat, out = commands.getstatusoutput(cmd)
if (stat):
raise Exception, "Error invoking 3ware Command Line Tool: " + str(out)
contList = []
for line in out.split("\n"):
line = line.strip()
if (line):
if (line.find("Controller") == 0):
# "Controller 1: 8506-4LP (4)"
contNo = line.split(" ")[1].split(":")[0]
contList.append(contNo)
elif (line[0] == "c"):
contNo = int(line.split(" ")[0][1:])
contList.append(contNo)
contList.sort()
return contList
def _test_MultipartWriter(self, onlyDirs):
contents = self._createMIMEMessage(onlyDirs)
self.assertTrue(contents, "No contents found")
self.assertTrue(contents.find("MIME-Version: 1.0") != -1, "Content is not a MIME message")
self.assertTrue(contents.find("Content-Type: multipart/mixed") != -1, "Content is not a multipart message")
# There should be a different boundaries declaration for each directory
# since each will result in a multipart message
nBoundaries = self._findOccurences(contents, 'boundary="')
self.assertEqual(nBoundaries, len(self.mydirs), "Didn't find all boundary definitions that were expected")
# There should be a "filename" declaration for each file
# since each will result in a MIME message inside one of the multiparts
if not onlyDirs:
nFilenames = self._findOccurences(contents, 'filename="')
self.assertEquals(nFilenames, len(self.myfiles), "Didn't find all filename definitions that were expected")
def lhcidrs(lip, hip):
"""Convert a range from lowip to highip to a set of address/mask values."""
r = []
while lip <= hip:
# algorithm:
# try successively smaller length blocks starting at lip
# until we find one that fits within lip,hip. add it to
# the list, set lip to one plus its end, keep going.
# we must insure that the chosen mask has lip as its proper
# lower end, and doesn't go lower.
lb = ffs(lip)
if lb == -1:
lb = 32
while lb >= 0:
(lt, ht) = cidrrange((lip, (32-lb)))
if lt == lip and ht <= hip:
break
lb = lb - 1
if lb < 0:
raise ArithmeticError, "something horribly wrong"
r.append((lip, (32-lb)))
lip = ht+1
return r
# This class handles network blocks.
def cidrstrerr(str):
"""Check an IP address or CIDR netblock for validity.
Returns None if it is and otherwise an error string."""
if not cvalid.match(str):
return 'Not a syntatically valid IP address or netblock'
rng = 32
pos = string.find(str, '/')
ips = str
if not pos == -1:
rng = string.atoi(ips[pos+1:])
ips = str[:pos]
if rng < 0 or rng > 32:
return 'CIDR length out of range'
n = string.split(ips, '.')
for i in n:
ip = string.atoi(i)
if (ip < 0 or ip > 255):
return 'an IP octet is out of range'
# could check to see if it is 'proper', but.
return None
def index(tagname):
"""Return the name of the submodule that tagname is defined in,
as well as a list of modules and keys in which this tagname is used."""
mods = glob.glob1(__path__[0], '*.py')
keys = []
usedin = {}
for m in mods:
if m[:2] == '__':
continue
modname = __name__ + '.' + m[:-3]
path = string.split(modname, '.')
module = __import__(modname)
# find the deepest submodule
for modname in path[1:]:
module = getattr(module, modname)
if hasattr(module, 'content'):
c = module.content
for k in c.keys():
if k == tagname:
keys.append(m)
for item in c[k]:
if string.find(item, tagname) != -1:
usedin[(m, k)] = 1
return keys, usedin.keys()
def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = string.find(sys.version, prefix)
if i == -1:
return 6
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
# I don't think paths are affected by minor version in version 6
if majorVersion == 6:
minorVersion = 0
if majorVersion >= 6:
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None
def find_library_file (self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
if debug:
try_names = [lib + "_d", lib]
else:
try_names = [lib]
for dir in dirs:
for name in try_names:
libfile = os.path.join(dir, self.library_filename (name))
if os.path.exists(libfile):
return libfile
else:
# Oops, didn't find it in *any* of 'dirs'
return None
# find_library_file ()
# Helper methods for using the MSVC registry settings
def find_exe(self, exe):
"""Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the original program name, 'exe'.
"""
for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
# didn't find it; try existing path
for p in string.split(os.environ['Path'],';'):
fn = os.path.join(os.path.abspath(p),exe)
if os.path.isfile(fn):
return fn
return exe
def get_msvcr():
"""Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later.
"""
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
if msc_ver == '1300':
# MSVC 7.0
return ['msvcr70']
elif msc_ver == '1310':
# MSVC 7.1
return ['msvcr71']
elif msc_ver == '1400':
# VS2005 / MSVC 8.0
return ['msvcr80']
elif msc_ver == '1500':
# VS2008 / MSVC 9.0
return ['msvcr90']
elif msc_ver == '1600':
# VS2010 / MSVC 10.0
return ['msvcr100']
else:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
def _readString(data):
"""Reads the next (null-terminated) block of data
"""
length = string.find(data,"\0")
nextData = int(math.ceil((length+1) / 4.0) * 4)
return (data[0:length], data[nextData:])
def _readString(data):
"""Reads the next (null-terminated) block of data
"""
length = string.find(data,"\0")
nextData = int(math.ceil((length+1) / 4.0) * 4)
return (data[0:length], data[nextData:])
def get_build_architecture():
"""Return the processor architecture.
Possible results are "Intel", "Itanium", or "AMD64".
"""
prefix = " bit ("
i = string.find(sys.version, prefix)
if i == -1:
return "Intel"
j = string.find(sys.version, ")", i)
return sys.version[i+len(prefix):j]
def find_library_file(self, dirs, lib, debug=0):
shortlib = '%s.lib' % lib
longlib = 'lib%s.lib' % lib # this form very rare
# get EMX's default library directory search path
try:
emx_dirs = os.environ['LIBRARY_PATH'].split(';')
except KeyError:
emx_dirs = []
for dir in dirs + emx_dirs:
shortlibp = os.path.join(dir, shortlib)
longlibp = os.path.join(dir, longlib)
if os.path.exists(shortlibp):
return shortlibp
elif os.path.exists(longlibp):
return longlibp
# Oops, didn't find it in *any* of 'dirs'
return None
# class EMXCCompiler
# Because these compilers aren't configured in Python's pyconfig.h file by
# default, we should at least warn the user if he is using a unmodified
# version.