File: frozenSupport.py

package info (click to toggle)
python-pyqtgraph 0.13.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,520 kB
  • sloc: python: 52,773; makefile: 115; ansic: 40; sh: 2
file content (55 lines) | stat: -rw-r--r-- 1,844 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
## Definitions helpful in frozen environments (eg py2exe)
import os
import sys
import zipfile


def listdir(path):
    """Replacement for os.listdir that works in frozen environments."""
    if not hasattr(sys, 'frozen'):
        return os.listdir(path)
    
    (zipPath, archivePath) = splitZip(path)
    if archivePath is None:
        return os.listdir(path)
    
    with zipfile.ZipFile(zipPath, "r") as zipobj:
        contents = zipobj.namelist()
    results = set()
    for name in contents:
        # components in zip archive paths are always separated by forward slash
        if name.startswith(archivePath) and len(name) > len(archivePath):
            name = name[len(archivePath):].split('/')[0]
            results.add(name)
    return list(results)

def isdir(path):
    """Replacement for os.path.isdir that works in frozen environments."""
    if not hasattr(sys, 'frozen'):
        return os.path.isdir(path)
    
    (zipPath, archivePath) = splitZip(path)
    if archivePath is None:
        return os.path.isdir(path)
    with zipfile.ZipFile(zipPath, "r") as zipobj:
        contents = zipobj.namelist()
    archivePath = archivePath.rstrip('/') + '/'   ## make sure there's exactly one '/' at the end
    for c in contents:
        if c.startswith(archivePath):
            return True
    return False
    
    
def splitZip(path):
    """Splits a path containing a zip file into (zipfile, subpath).
    If there is no zip file, returns (path, None)"""
    components = os.path.normpath(path).split(os.sep)
    for index, component in enumerate(components):
        if component.endswith('.zip'):
            zipPath = os.sep.join(components[0:index+1])
            archivePath = ''.join([x+'/' for x in components[index+1:]])
            return (zipPath, archivePath)
    else:
        return (path, None)