summaryrefslogtreecommitdiffstats
path: root/clear_comtypes_cache.py
blob: bd743cd55b0cce20b46d2d69811d3dcfcde15b11 (plain) (blame)
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
56
57
import os
import sys
import shutil

def get_next_cache_dir():
    work_dir = os.getcwd()
    try:
        # change working directory to avoid import from local folder
        # during installation process
        os.chdir(os.path.dirname(sys.executable))
        import comtypes.client
        return comtypes.client._code_cache._find_gen_dir()
    except ImportError:
        return None
    finally:
        os.chdir(work_dir)


def _remove(directory):
    shutil.rmtree(directory)
    print('Removed directory "%s"' % directory)


def remove_directory(directory, silent):
    if directory:
        if silent:
            _remove(directory)
        else:
            try:
                confirm = raw_input('Remove comtypes cache directories? (y/n): ')
            except NameError:
                confirm = input('Remove comtypes cache directories? (y/n): ')
            if confirm.lower() == 'y':
                _remove(directory)
            else:
                print('Directory "%s" NOT removed' % directory)
                return False
    return True


if len(sys.argv) > 1 and "-y" in sys.argv[1:]:
    silent = True
else:
    silent = False


# First iteration may get folder with restricted rights.
# Second iteration always gets temp cache folder (writable for all).
directory = get_next_cache_dir()
removed = remove_directory(directory, silent)

if removed:
    directory = get_next_cache_dir()

    # do not request the second confirmation
    # if the first folder was already removed
    remove_directory(directory, silent=removed)