install_python()   F
last analyzed

Complexity

Conditions 9

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
c 0
b 0
f 0
dl 0
loc 24
rs 3.4838
1
"""
2
AppVeyor will at least have few Pythons around so there's no point of implementing a bootstrapper in PowerShell.
3
4
This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1
5
with various fixes and improvements that just weren't feasible to implement in PowerShell.
6
"""
7
from __future__ import print_function
8
9
from os import environ
10
from os.path import exists
11
from subprocess import CalledProcessError
12
from subprocess import check_call
13
14
try:
15
    from urllib.request import urlretrieve
16
except ImportError:
17
    from urllib import urlretrieve
18
19
BASE_URL = "https://www.python.org/ftp/python/"
20
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
21
GET_PIP_PATH = "C:\get-pip.py"
22
URLS = {
23
    ("2.7", "64"): BASE_URL + "2.7.13/python-2.7.13.amd64.msi",
24
    ("2.7", "32"): BASE_URL + "2.7.13/python-2.7.13.msi",
25
    ("3.3", "64"): BASE_URL + "3.3.5/python-3.3.5.amd64.msi",
26
    ("3.3", "32"): BASE_URL + "3.3.5/python-3.3.5.msi",
27
    ("3.4", "64"): BASE_URL + "3.4.4/python-3.4.4.amd64.msi",
28
    ("3.4", "32"): BASE_URL + "3.4.4/python-3.4.4.msi",
29
    ("3.5", "64"): BASE_URL + "3.5.4/python-3.5.4-amd64.exe",
30
    ("3.5", "32"): BASE_URL + "3.5.4/python-3.5.4.exe",
31
    ("3.6", "64"): BASE_URL + "3.6.2/python-3.6.2-amd64.exe",
32
    ("3.6", "32"): BASE_URL + "3.6.2/python-3.6.2.exe",
33
}
34
INSTALL_CMD = {
35
    # Commands are allowed to fail only if they are not the last command.  Eg: uninstall (/x) allowed to fail.
36
    "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
37
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
38
    "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
39
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
40
    "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
41
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
42
    "3.5": [["{path}", "/quiet", "TargetDir={home}"]],
43
    "3.6": [["{path}", "/quiet", "TargetDir={home}"]],
44
}
45
46
47
def download_file(url, path):
48
    print("Downloading: {} (into {})".format(url, path))
49
    progress = [0, 0]
50
51
    def report(count, size, total):
52
        progress[0] = count * size
53
        if progress[0] - progress[1] > 1000000:
54
            progress[1] = progress[0]
55
            print("Downloaded {:,}/{:,} ...".format(progress[1], total))
56
57
    dest, _ = urlretrieve(url, path, reporthook=report)
58
    return dest
59
60
61
def install_python(version, arch, home):
62
    print("Installing Python", version, "for", arch, "bit architecture to", home)
63
    if exists(home):
64
        return
65
66
    path = download_python(version, arch)
67
    print("Installing", path, "to", home)
68
    success = False
69
    for cmd in INSTALL_CMD[version]:
70
        cmd = [part.format(home=home, path=path) for part in cmd]
71
        print("Running:", " ".join(cmd))
72
        try:
73
            check_call(cmd)
74
        except CalledProcessError as exc:
75
            print("Failed command", cmd, "with:", exc)
76
            if exists("install.log"):
77
                with open("install.log") as fh:
78
                    print(fh.read())
79
        else:
80
            success = True
81
    if success:
82
        print("Installation complete!")
83
    else:
84
        print("Installation failed")
85
86
87
def download_python(version, arch):
88
    for _ in range(3):
89
        try:
90
            return download_file(URLS[version, arch], "installer.exe")
91
        except Exception as exc:
92
            print("Failed to download:", exc)
93
        print("Retrying ...")
94
95
96
def install_pip(home):
97
    pip_path = home + "/Scripts/pip.exe"
98
    python_path = home + "/python.exe"
99
    if exists(pip_path):
100
        print("pip already installed.")
101
    else:
102
        print("Installing pip...")
103
        download_file(GET_PIP_URL, GET_PIP_PATH)
104
        print("Executing:", python_path, GET_PIP_PATH)
105
        check_call([python_path, GET_PIP_PATH])
106
107
108
def install_packages(home, *packages):
109
    cmd = [home + "/Scripts/pip.exe", "install"]
110
    cmd.extend(packages)
111
    check_call(cmd)
112
113
114
if __name__ == "__main__":
115
    install_python(environ['PYTHON_VERSION'], environ['PYTHON_ARCH'], environ['PYTHON_HOME'])
116
    install_pip(environ['PYTHON_HOME'])
117
    install_packages(environ['PYTHON_HOME'], "setuptools>=18.0.1", "wheel", "tox", "virtualenv>=13.1.0")
118