download_file()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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