Completed
Push — master ( 3c1059...41ee64 )
by Ionel Cristian
01:09
created

install_python()   F

Complexity

Conditions 9

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
c 1
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
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.7", "64"): BASE_URL + "2.7.10/python-2.7.10.amd64.msi",
22
    ("2.7", "32"): BASE_URL + "2.7.10/python-2.7.10.msi",
23
    # NOTE: no .msi installer for 3.3.6
24
    ("3.3", "64"): BASE_URL + "3.3.3/python-3.3.3.amd64.msi",
25
    ("3.3", "32"): BASE_URL + "3.3.3/python-3.3.3.msi",
26
    ("3.4", "64"): BASE_URL + "3.4.3/python-3.4.3.amd64.msi",
27
    ("3.4", "32"): BASE_URL + "3.4.3/python-3.4.3.msi",
28
    ("3.5", "64"): BASE_URL + "3.5.0/python-3.5.0-amd64.exe",
29
    ("3.5", "32"): BASE_URL + "3.5.0/python-3.5.0.exe",
30
}
31
INSTALL_CMD = {
32
    # Commands are allowed to fail only if they are not the last command.  Eg: uninstall (/x) allowed to fail.
33
    "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
34
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
35
    "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
36
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
37
    "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
38
            ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
39
    "3.5": [["{path}", "/quiet", "TargetDir={home}"]],
40
}
41
42
43
def download_file(url, path):
44
    print("Downloading: {} (into {})".format(url, path))
45
    progress = [0, 0]
46
47
    def report(count, size, total):
48
        progress[0] = count * size
49
        if progress[0] - progress[1] > 1000000:
50
            progress[1] = progress[0]
51
            print("Downloaded {:,}/{:,} ...".format(progress[1], total))
52
53
    dest, _ = urlretrieve(url, path, reporthook=report)
54
    return dest
55
56
57
def install_python(version, arch, home):
58
    print("Installing Python", version, "for", arch, "bit architecture to", home)
59
    if exists(home):
60
        return
61
62
    path = download_python(version, arch)
63
    print("Installing", path, "to", home)
64
    success = False
65
    for cmd in INSTALL_CMD[version]:
66
        cmd = [part.format(home=home, path=path) for part in cmd]
67
        print("Running:", " ".join(cmd))
68
        try:
69
            check_call(cmd)
70
        except Exception as exc:
71
            print("Failed command", cmd, "with:", exc)
72
            if exists("install.log"):
73
                with open("install.log") as fh:
74
                    print(fh.read())
75
        else:
76
            success = True
77
    if success:
78
        print("Installation complete!")
79
    else:
80
        print("Installation failed")
81
82
83
def download_python(version, arch):
84
    for _ in range(3):
85
        try:
86
            return download_file(URLS[version, arch], "installer.exe")
87
        except Exception as exc:
88
            print("Failed to download:", exc)
89
        print("Retrying ...")
90
91
92
def install_pip(home):
93
    pip_path = home + "/Scripts/pip.exe"
94
    python_path = home + "/python.exe"
95
    if exists(pip_path):
96
        print("pip already installed.")
97
    else:
98
        print("Installing pip...")
99
        download_file(GET_PIP_URL, GET_PIP_PATH)
100
        print("Executing:", python_path, GET_PIP_PATH)
101
        check_call([python_path, GET_PIP_PATH])
102
103
104
def install_packages(home, *packages):
105
    cmd = [home + "/Scripts/pip.exe", "install"]
106
    cmd.extend(packages)
107
    check_call(cmd)
108
109
110
if __name__ == "__main__":
111
    install_python(environ['PYTHON_VERSION'], environ['PYTHON_ARCH'], environ['PYTHON_HOME'])
112
    install_pip(environ['PYTHON_HOME'])
113
    install_packages(environ['PYTHON_HOME'], "setuptools>=18.0.1", "wheel", "tox", "virtualenv>=13.1.0")
114