Aluode/PerceptionLabPortable
0
1## Definitions helpful in frozen environments (eg py2exe)2import os3import sys4import zipfile5 6 7def listdir(path):8 """Replacement for os.listdir that works in frozen environments."""9 if not hasattr(sys, 'frozen'):10 return os.listdir(path)11 12 (zipPath, archivePath) = splitZip(path)13 if archivePath is None:14 return os.listdir(path)15 16 with zipfile.ZipFile(zipPath, "r") as zipobj:17 contents = zipobj.namelist()18 results = set()19 for name in contents:20 # components in zip archive paths are always separated by forward slash21 if name.startswith(archivePath) and len(name) > len(archivePath):22 name = name[len(archivePath):].split('/')[0]23 results.add(name)24 return list(results)25 26def isdir(path):27 """Replacement for os.path.isdir that works in frozen environments."""28 if not hasattr(sys, 'frozen'):29 return os.path.isdir(path)30 31 (zipPath, archivePath) = splitZip(path)32 if archivePath is None:33 return os.path.isdir(path)34 with zipfile.ZipFile(zipPath, "r") as zipobj:35 contents = zipobj.namelist()36 archivePath = archivePath.rstrip('/') + '/' ## make sure there's exactly one '/' at the end37 for c in contents:38 if c.startswith(archivePath):39 return True40 return False41 42 43def splitZip(path):44 """Splits a path containing a zip file into (zipfile, subpath).45 If there is no zip file, returns (path, None)"""46 components = os.path.normpath(path).split(os.sep)47 for index, component in enumerate(components):48 if component.endswith('.zip'):49 zipPath = os.sep.join(components[0:index+1])50 archivePath = ''.join([x+'/' for x in components[index+1:]])51 return (zipPath, archivePath)52 else:53 return (path, None)54 55 56 