Completed
Push — master ( 449e73...c6f33b )
by Ionel Cristian
01:09
created

install_python()   F

Complexity

Conditions 9

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 9
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
from os import environ
9
from os.path import exists
10
from subprocess import check_call
11
12
try:
13
    from urllib.request import urlretrieve
14
except ImportError:
15
    from urllib import urlretrieve
16
17
BASE_URL = "https://www.python.org/ftp/python/"
18
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
19
GET_PIP_PATH = "C:\get-pip.py"
20
URLS = {
21
    ("2.6", "64"): BASE_URL + "2.6.6/python-2.6.6.amd64.msi",
22
    ("2.6", "32"): BASE_URL + "2.6.6/python-2.6.6.msi",
23
    ("2.7", "64"): BASE_URL + "2.7.10/python-2.7.10.amd64.msi",
24
    ("2.7", "32"): BASE_URL + "2.7.10/python-2.7.10.msi",
25
    # NOTE: no .msi installer for 3.3.6
26
    ("3.3", "64"): BASE_URL + "3.3.3/python-3.3.3.amd64.msi",
27
    ("3.3", "32"): BASE_URL + "3.3.3/python-3.3.3.msi",
28
    ("3.4", "64"): BASE_URL + "3.4.3/python-3.4.3.amd64.msi",
29
    ("3.4", "32"): BASE_URL + "3.4.3/python-3.4.3.msi",
30
    ("3.5", "64"): BASE_URL + "3.5.0/python-3.5.0-amd64.exe",
31
    ("3.5", "32"): BASE_URL + "3.5.0/python-3.5.0.exe",
32
}
33
INSTALL_CMD = {
34
    # Commands are allowed to fail only if they are not the last command.  Eg: uninstall (/x) allowed to fail.
35
    "2.6": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
36
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
37
    "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
38
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
39
    "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
40
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
41
    "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
42
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
43
    "3.5": [["{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 Exception 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