Advertisement
TylerB

Untitled

Feb 23rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 44.87 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2012-2016 Matt Martz
  4. # All Rights Reserved.
  5. #
  6. #    Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. #    not use this file except in compliance with the License. You may obtain
  8. #    a copy of the License at
  9. #
  10. #         http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. #    Unless required by applicable law or agreed to in writing, software
  13. #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. #    License for the specific language governing permissions and limitations
  16. #    under the License.
  17.  
  18. import os
  19. import re
  20. import csv
  21. import sys
  22. import math
  23. import errno
  24. import signal
  25. import socket
  26. import timeit
  27. import datetime
  28. import platform
  29. import threading
  30. import xml.parsers.expat
  31.  
  32. try:
  33.     import gzip
  34.     GZIP_BASE = gzip.GzipFile
  35. except ImportError:
  36.     gzip = None
  37.     GZIP_BASE = object
  38.  
  39. __version__ = '1.0.2'
  40.  
  41.  
  42. class FakeShutdownEvent(object):
  43.     """Class to fake a threading.Event.isSet so that users of this module
  44.    are not required to register their own threading.Event()
  45.    """
  46.  
  47.     @staticmethod
  48.     def isSet():
  49.         "Dummy method to always return false"""
  50.         return False
  51.  
  52.  
  53. # Some global variables we use
  54. USER_AGENT = None
  55. SOURCE = None
  56. SHUTDOWN_EVENT = FakeShutdownEvent()
  57. SCHEME = 'http'
  58. DEBUG = False
  59.  
  60. # Used for bound_interface
  61. SOCKET_SOCKET = socket.socket
  62.  
  63. # Begin import game to handle Python 2 and Python 3
  64. try:
  65.     import json
  66. except ImportError:
  67.     try:
  68.         import simplejson as json
  69.     except ImportError:
  70.         json = None
  71.  
  72. try:
  73.     import xml.etree.cElementTree as ET
  74. except ImportError:
  75.     try:
  76.         import xml.etree.ElementTree as ET
  77.     except ImportError:
  78.         from xml.dom import minidom as DOM
  79.         ET = None
  80.  
  81. try:
  82.     from urllib2 import urlopen, Request, HTTPError, URLError
  83. except ImportError:
  84.     from urllib.request import urlopen, Request, HTTPError, URLError
  85.  
  86. try:
  87.     from httplib import HTTPConnection
  88. except ImportError:
  89.     from http.client import HTTPConnection
  90.  
  91. try:
  92.     from httplib import HTTPSConnection
  93. except ImportError:
  94.     try:
  95.         from http.client import HTTPSConnection
  96.     except ImportError:
  97.         HTTPSConnection = None
  98.  
  99. try:
  100.     from Queue import Queue
  101. except ImportError:
  102.     from queue import Queue
  103.  
  104. try:
  105.     from urlparse import urlparse
  106. except ImportError:
  107.     from urllib.parse import urlparse
  108.  
  109. try:
  110.     from urlparse import parse_qs
  111. except ImportError:
  112.     try:
  113.         from urllib.parse import parse_qs
  114.     except ImportError:
  115.         from cgi import parse_qs
  116.  
  117. try:
  118.     from hashlib import md5
  119. except ImportError:
  120.     from md5 import md5
  121.  
  122. try:
  123.     from argparse import ArgumentParser as ArgParser
  124.     from argparse import SUPPRESS as ARG_SUPPRESS
  125.     PARSER_TYPE_INT = int
  126.     PARSER_TYPE_STR = str
  127. except ImportError:
  128.     from optparse import OptionParser as ArgParser
  129.     from optparse import SUPPRESS_HELP as ARG_SUPPRESS
  130.     PARSER_TYPE_INT = 'int'
  131.     PARSER_TYPE_STR = 'string'
  132.  
  133. try:
  134.     from cStringIO import StringIO
  135.     BytesIO = None
  136. except ImportError:
  137.     try:
  138.         from io import StringIO, BytesIO
  139.     except ImportError:
  140.         from StringIO import StringIO
  141.         BytesIO = None
  142.  
  143. try:
  144.     import builtins
  145. except ImportError:
  146.     def print_(*args, **kwargs):
  147.         """The new-style print function for Python 2.4 and 2.5.
  148.  
  149.        Taken from https://pypi.python.org/pypi/six/
  150.  
  151.        Modified to set encoding to UTF-8 if not set when stdout may not be
  152.        a tty such as when piping to head
  153.        """
  154.         fp = kwargs.pop("file", sys.stdout)
  155.         if fp is None:
  156.             return
  157.  
  158.         def write(data):
  159.             if not isinstance(data, basestring):
  160.                 data = str(data)
  161.             # If the file has an encoding, encode unicode with it.
  162.             encoding = fp.encoding or 'UTF-8'  # Diverges for notty
  163.             if (isinstance(fp, file) and
  164.                     isinstance(data, unicode) and
  165.                     encoding is not None):
  166.                 errors = getattr(fp, "errors", None)
  167.                 if errors is None:
  168.                     errors = "strict"
  169.                 data = data.encode(encoding, errors)
  170.             fp.write(data)
  171.         want_unicode = False
  172.         sep = kwargs.pop("sep", None)
  173.         if sep is not None:
  174.             if isinstance(sep, unicode):
  175.                 want_unicode = True
  176.             elif not isinstance(sep, str):
  177.                 raise TypeError("sep must be None or a string")
  178.         end = kwargs.pop("end", None)
  179.         if end is not None:
  180.             if isinstance(end, unicode):
  181.                 want_unicode = True
  182.             elif not isinstance(end, str):
  183.                 raise TypeError("end must be None or a string")
  184.         if kwargs:
  185.             raise TypeError("invalid keyword arguments to print()")
  186.         if not want_unicode:
  187.             for arg in args:
  188.                 if isinstance(arg, unicode):
  189.                     want_unicode = True
  190.                     break
  191.         if want_unicode:
  192.             newline = unicode("\n")
  193.             space = unicode(" ")
  194.         else:
  195.             newline = "\n"
  196.             space = " "
  197.         if sep is None:
  198.             sep = space
  199.         if end is None:
  200.             end = newline
  201.         for i, arg in enumerate(args):
  202.             if i:
  203.                 write(sep)
  204.             write(arg)
  205.         write(end)
  206. else:
  207.     print_ = getattr(builtins, 'print')
  208.     del builtins
  209.  
  210. # Exception "constants" to support Python 2 through Python 3
  211. try:
  212.     import ssl
  213.     try:
  214.         CERT_ERROR = (ssl.CertificateError,)
  215.     except AttributeError:
  216.         CERT_ERROR = tuple()
  217.  
  218.     HTTP_ERRORS = ((HTTPError, URLError, socket.error, ssl.SSLError) +
  219.                    CERT_ERROR)
  220. except ImportError:
  221.     HTTP_ERRORS = (HTTPError, URLError, socket.error)
  222.  
  223.  
  224. class SpeedtestException(Exception):
  225.     """Base exception for this module"""
  226.  
  227.  
  228. class SpeedtestCLIError(SpeedtestException):
  229.     """Generic exception for raising errors during CLI operation"""
  230.  
  231.  
  232. class SpeedtestHTTPError(SpeedtestException):
  233.     """Base HTTP exception for this module"""
  234.  
  235.  
  236. class SpeedtestConfigError(SpeedtestException):
  237.     """Configuration provided is invalid"""
  238.  
  239.  
  240. class ConfigRetrievalError(SpeedtestHTTPError):
  241.     """Could not retrieve config.php"""
  242.  
  243.  
  244. class ServersRetrievalError(SpeedtestHTTPError):
  245.     """Could not retrieve speedtest-servers.php"""
  246.  
  247.  
  248. class InvalidServerIDType(SpeedtestException):
  249.     """Server ID used for filtering was not an integer"""
  250.  
  251.  
  252. class NoMatchedServers(SpeedtestException):
  253.     """No servers matched when filtering"""
  254.  
  255.  
  256. class SpeedtestMiniConnectFailure(SpeedtestException):
  257.     """Could not connect to the provided speedtest mini server"""
  258.  
  259.  
  260. class InvalidSpeedtestMiniServer(SpeedtestException):
  261.     """Server provided as a speedtest mini server does not actually appear
  262.    to be a speedtest mini server
  263.    """
  264.  
  265.  
  266. class ShareResultsConnectFailure(SpeedtestException):
  267.     """Could not connect to speedtest.net API to POST results"""
  268.  
  269.  
  270. class ShareResultsSubmitFailure(SpeedtestException):
  271.     """Unable to successfully POST results to speedtest.net API after
  272.    connection
  273.    """
  274.  
  275.  
  276. class SpeedtestUploadTimeout(SpeedtestException):
  277.     """testlength configuration reached during upload
  278.    Used to ensure the upload halts when no additional data should be sent
  279.    """
  280.  
  281.  
  282. class SpeedtestBestServerFailure(SpeedtestException):
  283.     """Unable to determine best server"""
  284.  
  285.  
  286. class GzipDecodedResponse(GZIP_BASE):
  287.     """A file-like object to decode a response encoded with the gzip
  288.    method, as described in RFC 1952.
  289.  
  290.    Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified
  291.    to work for py2.4-py3
  292.    """
  293.     def __init__(self, response):
  294.         # response doesn't support tell() and read(), required by
  295.        # GzipFile
  296.        if not gzip:
  297.            raise SpeedtestHTTPError('HTTP response body is gzip encoded, '
  298.                                     'but gzip support is not available')
  299.        IO = BytesIO or StringIO
  300.        self.io = IO()
  301.        while 1:
  302.            chunk = response.read(1024)
  303.            if len(chunk) == 0:
  304.                break
  305.            self.io.write(chunk)
  306.        self.io.seek(0)
  307.        gzip.GzipFile.__init__(self, mode='rb', fileobj=self.io)
  308.  
  309.    def close(self):
  310.        try:
  311.            gzip.GzipFile.close(self)
  312.        finally:
  313.            self.io.close()
  314.  
  315.  
  316. def get_exception():
  317.    """Helper function to work with py2.4-py3 for getting the current
  318.    exception in a try/except block
  319.    """
  320.    return sys.exc_info()[1]
  321.  
  322.  
  323. def bound_socket(*args, **kwargs):
  324.    """Bind socket to a specified source IP address"""
  325.  
  326.    sock = SOCKET_SOCKET(*args, **kwargs)
  327.    sock.bind((SOURCE, 0))
  328.    return sock
  329.  
  330.  
  331. def distance(origin, destination):
  332.    """Determine distance between 2 sets of [lat,lon] in km"""
  333.  
  334.    lat1, lon1 = origin
  335.    lat2, lon2 = destination
  336.    radius = 6371  # km
  337.  
  338.    dlat = math.radians(lat2 - lat1)
  339.    dlon = math.radians(lon2 - lon1)
  340.    a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
  341.         math.cos(math.radians(lat1)) *
  342.         math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
  343.         math.sin(dlon / 2))
  344.    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  345.    d = radius * c
  346.  
  347.    return d
  348.  
  349.  
  350. def build_user_agent():
  351.    """Build a Mozilla/5.0 compatible User-Agent string"""
  352.  
  353.    global USER_AGENT
  354.    if USER_AGENT:
  355.        return USER_AGENT
  356.  
  357.    ua_tuple = (
  358.        'Mozilla/5.0',
  359.        '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]),
  360.        'Python/%s' % platform.python_version(),
  361.        '(KHTML, like Gecko)',
  362.        'speedtest-cli/%s' % __version__
  363.    )
  364.    USER_AGENT = ' '.join(ua_tuple)
  365.    printer(USER_AGENT, debug=True)
  366.    return USER_AGENT
  367.  
  368.  
  369. def build_request(url, data=None, headers=None, bump=''):
  370.    """Build a urllib2 request object
  371.  
  372.    This function automatically adds a User-Agent header to all requests
  373.  
  374.    """
  375.  
  376.    if not USER_AGENT:
  377.        build_user_agent()
  378.  
  379.    if not headers:
  380.        headers = {}
  381.  
  382.    if url[0] == ':':
  383.        schemed_url = '%s%s' % (SCHEME, url)
  384.    else:
  385.        schemed_url = url
  386.  
  387.    if '?' in url:
  388.        delim = '&'
  389.    else:
  390.        delim = '?'
  391.  
  392.    # WHO YOU GONNA CALL? CACHE BUSTERS!
  393.    final_url = '%s%sx=%s.%s' % (schemed_url, delim,
  394.                                 int(timeit.time.time() * 1000),
  395.                                 bump)
  396.  
  397.    headers.update({
  398.        'User-Agent': USER_AGENT,
  399.        'Cache-Control': 'no-cache',
  400.    })
  401.  
  402.    printer('%s %s' % (('GET', 'POST')[bool(data)], final_url),
  403.            debug=True)
  404.  
  405.    return Request(final_url, data=data, headers=headers)
  406.  
  407.  
  408. def catch_request(request):
  409.    """Helper function to catch common exceptions encountered when
  410.    establishing a connection with a HTTP/HTTPS request
  411.  
  412.    """
  413.  
  414.    try:
  415.        uh = urlopen(request)
  416.        return uh, False
  417.    except HTTP_ERRORS:
  418.        e = get_exception()
  419.        return None, e
  420.  
  421.  
  422. def get_response_stream(response):
  423.    """Helper function to return either a Gzip reader if
  424.    ``Content-Encoding`` is ``gzip`` otherwise the response itself
  425.  
  426.    """
  427.  
  428.    try:
  429.        getheader = response.headers.getheader
  430.    except AttributeError:
  431.        getheader = response.getheader
  432.  
  433.    if getheader('content-encoding') == 'gzip':
  434.        return GzipDecodedResponse(response)
  435.  
  436.    return response
  437.  
  438.  
  439. def get_attributes_by_tag_name(dom, tag_name):
  440.    """Retrieve an attribute from an XML document and return it in a
  441.    consistent format
  442.  
  443.    Only used with xml.dom.minidom, which is likely only to be used
  444.    with python versions older than 2.5
  445.    """
  446.    elem = dom.getElementsByTagName(tag_name)[0]
  447.    return dict(list(elem.attributes.items()))
  448.  
  449.  
  450. def print_dots(current, total, start=False, end=False):
  451.    """Built in callback function used by Thread classes for printing
  452.    status
  453.    """
  454.  
  455.    if SHUTDOWN_EVENT.isSet():
  456.        return
  457.  
  458.    sys.stdout.write('.')
  459.    if current + 1 == total and end is True:
  460.        sys.stdout.write('\n')
  461.    sys.stdout.flush()
  462.  
  463.  
  464. def do_nothing(*args, **kwargs):
  465.    pass
  466.  
  467.  
  468. class HTTPDownloader(threading.Thread):
  469.    """Thread class for retrieving a URL"""
  470.  
  471.    def __init__(self, i, request, start, timeout):
  472.        threading.Thread.__init__(self)
  473.        self.request = request
  474.        self.result = [0]
  475.        self.starttime = start
  476.        self.timeout = timeout
  477.        self.i = i
  478.  
  479.    def run(self):
  480.        try:
  481.            if (timeit.default_timer() - self.starttime) <= self.timeout:
  482.                f = urlopen(self.request)
  483.                while (not SHUTDOWN_EVENT.isSet() and
  484.                        (timeit.default_timer() - self.starttime) <=
  485.                        self.timeout):
  486.                    self.result.append(len(f.read(10240)))
  487.                    if self.result[-1] == 0:
  488.                        break
  489.                f.close()
  490.        except IOError:
  491.            pass
  492.  
  493.  
  494. class HTTPUploaderData(object):
  495.    """File like object to improve cutting off the upload once the timeout
  496.    has been reached
  497.    """
  498.  
  499.    def __init__(self, length, start, timeout):
  500.        self.length = length
  501.        self.start = start
  502.        self.timeout = timeout
  503.  
  504.        self._data = None
  505.  
  506.        self.total = [0]
  507.  
  508.    def _create_data(self):
  509.        chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  510.        multiplier = int(round(int(self.length) / 36.0))
  511.        IO = BytesIO or StringIO
  512.        self._data = IO(
  513.            ('content1=%s' %
  514.             (chars * multiplier)[0:int(self.length) - 9]
  515.             ).encode()
  516.        )
  517.  
  518.    @property
  519.    def data(self):
  520.        if not self._data:
  521.            self._create_data()
  522.        return self._data
  523.  
  524.    def read(self, n=10240):
  525.        if ((timeit.default_timer() - self.start) <= self.timeout and
  526.                not SHUTDOWN_EVENT.isSet()):
  527.            chunk = self.data.read(n)
  528.            self.total.append(len(chunk))
  529.            return chunk
  530.        else:
  531.            raise SpeedtestUploadTimeout
  532.  
  533.    def __len__(self):
  534.        return self.length
  535.  
  536.  
  537. class HTTPUploader(threading.Thread):
  538.    """Thread class for putting a URL"""
  539.  
  540.    def __init__(self, i, request, start, size, timeout):
  541.        threading.Thread.__init__(self)
  542.        self.request = request
  543.        self.request.data.start = self.starttime = start
  544.        self.size = size
  545.        self.result = None
  546.        self.timeout = timeout
  547.        self.i = i
  548.  
  549.    def run(self):
  550.        request = self.request
  551.        try:
  552.            if ((timeit.default_timer() - self.starttime) <= self.timeout and
  553.                    not SHUTDOWN_EVENT.isSet()):
  554.                try:
  555.                    f = urlopen(request)
  556.                except TypeError:
  557.                    # PY24 expects a string or buffer
  558.                    # This also causes issues with Ctrl-C, but we will concede
  559.                    # for the moment that Ctrl-C on PY24 isn't immediate
  560.                     request = build_request(self.request.get_full_url(),
  561.                                             data=request.data.read(self.size))
  562.                     f = urlopen(request)
  563.                 f.read(11)
  564.                 f.close()
  565.                 self.result = sum(self.request.data.total)
  566.             else:
  567.                 self.result = 0
  568.         except (IOError, SpeedtestUploadTimeout):
  569.             self.result = sum(self.request.data.total)
  570.  
  571.  
  572. class SpeedtestResults(object):
  573.     """Class for holding the results of a speedtest, including:
  574.  
  575.    Download speed
  576.    Upload speed
  577.    Ping/Latency to test server
  578.    Data about server that the test was run against
  579.  
  580.    Additionally this class can return a result data as a dictionary or CSV,
  581.    as well as submit a POST of the result data to the speedtest.net API
  582.    to get a share results image link.
  583.    """
  584.  
  585.     def __init__(self, download=0, upload=0, ping=0, server=None):
  586.         self.download = download
  587.         self.upload = upload
  588.         self.ping = ping
  589.         if server is None:
  590.             self.server = {}
  591.         else:
  592.             self.server = server
  593.         self._share = None
  594.         self.timestamp = datetime.datetime.utcnow().isoformat()
  595.         self.bytes_received = 0
  596.         self.bytes_sent = 0
  597.  
  598.     def __repr__(self):
  599.         return repr(self.dict())
  600.  
  601.     def share(self):
  602.         """POST data to the speedtest.net API to obtain a share results
  603.        link
  604.        """
  605.  
  606.         if self._share:
  607.             return self._share
  608.  
  609.         download = int(round(self.download / 1000.0, 0))
  610.         ping = int(round(self.ping, 0))
  611.         upload = int(round(self.upload / 1000.0, 0))
  612.  
  613.         # Build the request to send results back to speedtest.net
  614.         # We use a list instead of a dict because the API expects parameters
  615.         # in a certain order
  616.         api_data = [
  617.             'recommendedserverid=%s' % self.server['id'],
  618.             'ping=%s' % ping,
  619.             'screenresolution=',
  620.             'promo=',
  621.             'download=%s' % download,
  622.             'screendpi=',
  623.             'upload=%s' % upload,
  624.             'testmethod=http',
  625.             'hash=%s' % md5(('%s-%s-%s-%s' %
  626.                              (ping, upload, download, '297aae72'))
  627.                             .encode()).hexdigest(),
  628.             'touchscreen=none',
  629.             'startmode=pingselect',
  630.             'accuracy=1',
  631.             'bytesreceived=%s' % self.bytes_received,
  632.             'bytessent=%s' % self.bytes_sent,
  633.             'serverid=%s' % self.server['id'],
  634.         ]
  635.  
  636.         headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'}
  637.         request = build_request('://www.speedtest.net/api/api.php',
  638.                                 data='&'.join(api_data).encode(),
  639.                                 headers=headers)
  640.         f, e = catch_request(request)
  641.         if e:
  642.             raise ShareResultsConnectFailure(e)
  643.  
  644.         response = f.read()
  645.         code = f.code
  646.         f.close()
  647.  
  648.         if int(code) != 200:
  649.             raise ShareResultsSubmitFailure('Could not submit results to '
  650.                                             'speedtest.net')
  651.  
  652.         qsargs = parse_qs(response.decode())
  653.         resultid = qsargs.get('resultid')
  654.         if not resultid or len(resultid) != 1:
  655.             raise ShareResultsSubmitFailure('Could not submit results to '
  656.                                             'speedtest.net')
  657.  
  658.         self._share = 'http://www.speedtest.net/result/%s.png' % resultid[0]
  659.  
  660.         return self._share
  661.  
  662.     def dict(self):
  663.         """Return dictionary of result data"""
  664.  
  665.         return {
  666.             'download': self.download,
  667.             'upload': self.upload,
  668.             'ping': self.ping,
  669.             'server': self.server,
  670.             'timestamp': self.timestamp
  671.         }
  672.  
  673.     def csv(self, delimiter=','):
  674.         """Return data in CSV format"""
  675.  
  676.         data = self.dict()
  677.         out = StringIO()
  678.         writer = csv.writer(out, delimiter=delimiter, lineterminator='')
  679.         writer.writerow([data['server']['id'], data['server']['sponsor'],
  680.                          data['server']['name'], data['timestamp'],
  681.                          data['server']['d'], data['ping'], data['download'],
  682.                          data['upload']])
  683.         return out.getvalue()
  684.  
  685.     def json(self, pretty=False):
  686.         """Return data in JSON format"""
  687.  
  688.         kwargs = {}
  689.         if pretty:
  690.             kwargs.update({
  691.                 'indent': 4,
  692.                 'sort_keys': True
  693.             })
  694.         return json.dumps(self.dict(), **kwargs)
  695.  
  696.  
  697. class Speedtest(object):
  698.     """Class for performing standard speedtest.net testing operations"""
  699.  
  700.     def __init__(self, config=None):
  701.         self.config = {}
  702.         self.get_config()
  703.         if config is not None:
  704.             self.config.update(config)
  705.  
  706.         self.servers = {}
  707.         self.closest = []
  708.         self.best = {}
  709.  
  710.         self.results = SpeedtestResults()
  711.  
  712.     def get_config(self):
  713.         """Download the speedtest.net configuration and return only the data
  714.        we are interested in
  715.        """
  716.  
  717.         headers = {}
  718.         if gzip:
  719.             headers['Accept-Encoding'] = 'gzip'
  720.         request = build_request('://www.speedtest.net/speedtest-config.php',
  721.                                 headers=headers)
  722.         uh, e = catch_request(request)
  723.         if e:
  724.             raise ConfigRetrievalError(e)
  725.         configxml = []
  726.  
  727.         stream = get_response_stream(uh)
  728.  
  729.         while 1:
  730.             configxml.append(stream.read(1024))
  731.             if len(configxml[-1]) == 0:
  732.                 break
  733.         stream.close()
  734.         uh.close()
  735.  
  736.         if int(uh.code) != 200:
  737.             return None
  738.  
  739.         printer(''.encode().join(configxml), debug=True)
  740.  
  741.         try:
  742.             root = ET.fromstring(''.encode().join(configxml))
  743.             server_config = root.find('server-config').attrib
  744.             download = root.find('download').attrib
  745.             upload = root.find('upload').attrib
  746.             # times = root.find('times').attrib
  747.             client = root.find('client').attrib
  748.  
  749.         except AttributeError:
  750.             root = DOM.parseString(''.join(configxml))
  751.             server_config = get_attributes_by_tag_name(root, 'server-config')
  752.             download = get_attributes_by_tag_name(root, 'download')
  753.             upload = get_attributes_by_tag_name(root, 'upload')
  754.             # times = get_attributes_by_tag_name(root, 'times')
  755.             client = get_attributes_by_tag_name(root, 'client')
  756.  
  757.         ignore_servers = list(
  758.             map(int, server_config['ignoreids'].split(','))
  759.         )
  760.  
  761.         ratio = int(upload['ratio'])
  762.         upload_max = int(upload['maxchunkcount'])
  763.         up_sizes = [32768, 65536, 131072, 262144, 524288, 1048576, 7340032]
  764.         sizes = {
  765.             'upload': up_sizes[ratio - 1:],
  766.             'download': [350, 500, 750, 1000, 1500, 2000, 2500,
  767.                          3000, 3500, 4000]
  768.         }
  769.  
  770.         counts = {
  771.             'upload': int(upload_max * 2 / len(sizes['upload'])),
  772.             'download': int(download['threadsperurl'])
  773.         }
  774.  
  775.         threads = {
  776.             'upload': int(upload['threads']),
  777.             'download': int(server_config['threadcount']) * 2
  778.         }
  779.  
  780.         length = {
  781.             'upload': int(upload['testlength']),
  782.             'download': int(download['testlength'])
  783.         }
  784.  
  785.         self.config.update({
  786.             'client': client,
  787.             'ignore_servers': ignore_servers,
  788.             'sizes': sizes,
  789.             'counts': counts,
  790.             'threads': threads,
  791.             'length': length,
  792.             'upload_max': upload_max
  793.         })
  794.  
  795.         self.lat_lon = (float(client['lat']), float(client['lon']))
  796.  
  797.         return self.config
  798.  
  799.     def get_servers(self, servers=None):
  800.         """Retrieve a the list of speedtest.net servers, optionally filtered
  801.        to servers matching those specified in the ``servers`` argument
  802.        """
  803.         if servers is None:
  804.             servers = []
  805.  
  806.         self.servers.clear()
  807.  
  808.         for i, s in enumerate(servers):
  809.             try:
  810.                 servers[i] = int(s)
  811.             except ValueError:
  812.                 raise InvalidServerIDType('%s is an invalid server type, must '
  813.                                           'be int' % s)
  814.  
  815.         urls = [
  816.             '://www.speedtest.net/speedtest-servers-static.php',
  817.             'http://c.speedtest.net/speedtest-servers-static.php',
  818.             '://www.speedtest.net/speedtest-servers.php',
  819.             'http://c.speedtest.net/speedtest-servers.php',
  820.         ]
  821.  
  822.         headers = {}
  823.         if gzip:
  824.             headers['Accept-Encoding'] = 'gzip'
  825.  
  826.         errors = []
  827.         for url in urls:
  828.             try:
  829.                 request = build_request('%s?threads=%s' %
  830.                                         (url,
  831.                                          self.config['threads']['download']),
  832.                                         headers=headers)
  833.                 uh, e = catch_request(request)
  834.                 if e:
  835.                     errors.append('%s' % e)
  836.                     raise ServersRetrievalError
  837.  
  838.                 stream = get_response_stream(uh)
  839.  
  840.                 serversxml = []
  841.                 while 1:
  842.                     serversxml.append(stream.read(1024))
  843.                     if len(serversxml[-1]) == 0:
  844.                         break
  845.  
  846.                 stream.close()
  847.                 uh.close()
  848.  
  849.                 if int(uh.code) != 200:
  850.                     raise ServersRetrievalError
  851.  
  852.                 printer(''.encode().join(serversxml), debug=True)
  853.  
  854.                 try:
  855.                     try:
  856.                         root = ET.fromstring(''.encode().join(serversxml))
  857.                         elements = root.getiterator('server')
  858.                     except AttributeError:
  859.                         root = DOM.parseString(''.join(serversxml))
  860.                         elements = root.getElementsByTagName('server')
  861.                 except (SyntaxError, xml.parsers.expat.ExpatError):
  862.                     raise ServersRetrievalError
  863.  
  864.                 for server in elements:
  865.                     try:
  866.                         attrib = server.attrib
  867.                     except AttributeError:
  868.                         attrib = dict(list(server.attributes.items()))
  869.  
  870.                     if servers and int(attrib.get('id')) not in servers:
  871.                         continue
  872.  
  873.                     if int(attrib.get('id')) in self.config['ignore_servers']:
  874.                         continue
  875.  
  876.                     try:
  877.                         d = distance(self.lat_lon,
  878.                                      (float(attrib.get('lat')),
  879.                                       float(attrib.get('lon'))))
  880.                     except:
  881.                         continue
  882.  
  883.                     attrib['d'] = d
  884.  
  885.                     try:
  886.                         self.servers[d].append(attrib)
  887.                     except KeyError:
  888.                         self.servers[d] = [attrib]
  889.  
  890.                 printer(''.encode().join(serversxml), debug=True)
  891.  
  892.                 break
  893.  
  894.             except ServersRetrievalError:
  895.                 continue
  896.  
  897.         if servers and not self.servers:
  898.             raise NoMatchedServers
  899.  
  900.         return self.servers
  901.  
  902.     def set_mini_server(self, server):
  903.         """Instead of querying for a list of servers, set a link to a
  904.        speedtest mini server
  905.        """
  906.  
  907.         urlparts = urlparse(server)
  908.  
  909.         name, ext = os.path.splitext(urlparts[2])
  910.         if ext:
  911.             url = os.path.dirname(server)
  912.         else:
  913.             url = server
  914.  
  915.         request = build_request(url)
  916.         uh, e = catch_request(request)
  917.         if e:
  918.             raise SpeedtestMiniConnectFailure('Failed to connect to %s' %
  919.                                               server)
  920.         else:
  921.             text = uh.read()
  922.             uh.close()
  923.  
  924.         extension = re.findall('upload_?[Ee]xtension: "([^"]+)"',
  925.                                text.decode())
  926.         if not extension:
  927.             for ext in ['php', 'asp', 'aspx', 'jsp']:
  928.                 try:
  929.                     f = urlopen('%s/speedtest/upload.%s' % (url, ext))
  930.                 except:
  931.                     pass
  932.                 else:
  933.                     data = f.read().strip().decode()
  934.                     if (f.code == 200 and
  935.                             len(data.splitlines()) == 1 and
  936.                             re.match('size=[0-9]', data)):
  937.                         extension = [ext]
  938.                         break
  939.         if not urlparts or not extension:
  940.             raise InvalidSpeedtestMiniServer('Invalid Speedtest Mini Server: '
  941.                                              '%s' % server)
  942.  
  943.         self.servers = [{
  944.             'sponsor': 'Speedtest Mini',
  945.             'name': urlparts[1],
  946.             'd': 0,
  947.             'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]),
  948.             'latency': 0,
  949.             'id': 0
  950.         }]
  951.  
  952.         return self.servers
  953.  
  954.     def get_closest_servers(self, limit=5):
  955.         """Limit servers to the closest speedtest.net servers based on
  956.        geographic distance
  957.        """
  958.  
  959.         if not self.servers:
  960.             self.get_servers()
  961.  
  962.         for d in sorted(self.servers.keys()):
  963.             for s in self.servers[d]:
  964.                 self.closest.append(s)
  965.                 if len(self.closest) == limit:
  966.                     break
  967.             else:
  968.                 continue
  969.             break
  970.  
  971.         printer(self.closest, debug=True)
  972.         return self.closest
  973.  
  974.     def get_best_server(self, servers=None):
  975.         """Perform a speedtest.net "ping" to determine which speedtest.net
  976.        server has the lowest latency
  977.        """
  978.  
  979.         if not servers:
  980.             if not self.closest:
  981.                 servers = self.get_closest_servers()
  982.             servers = self.closest
  983.  
  984.         results = {}
  985.         for server in servers:
  986.             cum = []
  987.             url = os.path.dirname(server['url'])
  988.             urlparts = urlparse('%s/latency.txt' % url)
  989.             printer('%s %s/latency.txt' % ('GET', url), debug=True)
  990.             for _ in range(0, 3):
  991.                 try:
  992.                     if urlparts[0] == 'https':
  993.                         h = HTTPSConnection(urlparts[1])
  994.                     else:
  995.                         h = HTTPConnection(urlparts[1])
  996.                     headers = {'User-Agent': USER_AGENT}
  997.                     start = timeit.default_timer()
  998.                     h.request("GET", urlparts[2], headers=headers)
  999.                     r = h.getresponse()
  1000.                     total = (timeit.default_timer() - start)
  1001.                 except HTTP_ERRORS:
  1002.                     e = get_exception()
  1003.                     printer('%r' % e, debug=True)
  1004.                     cum.append(3600)
  1005.                     continue
  1006.  
  1007.                 text = r.read(9)
  1008.                 if int(r.status) == 200 and text == 'test=test'.encode():
  1009.                     cum.append(total)
  1010.                 else:
  1011.                     cum.append(3600)
  1012.                 h.close()
  1013.  
  1014.             avg = round((sum(cum) / 6) * 1000.0, 3)
  1015.             results[avg] = server
  1016.  
  1017.         try:
  1018.             fastest = sorted(results.keys())[0]
  1019.         except IndexError:
  1020.             raise SpeedtestBestServerFailure('Unable to connect to servers to '
  1021.                                              'test latency.')
  1022.         best = results[fastest]
  1023.         best['latency'] = fastest
  1024.  
  1025.         self.results.ping = fastest
  1026.         self.results.server = best
  1027.  
  1028.         self.best.update(best)
  1029.         printer(best, debug=True)
  1030.         return best
  1031.  
  1032.     def download(self, callback=do_nothing):
  1033.         """Test download speed against speedtest.net"""
  1034.  
  1035.         urls = []
  1036.         for size in self.config['sizes']['download']:
  1037.             for _ in range(0, self.config['counts']['download']):
  1038.                 urls.append('%s/random%sx%s.jpg' %
  1039.                             (os.path.dirname(self.best['url']), size, size))
  1040.  
  1041.         request_count = len(urls)
  1042.         requests = []
  1043.         for i, url in enumerate(urls):
  1044.             requests.append(build_request(url, bump=i))
  1045.  
  1046.         def producer(q, requests, request_count):
  1047.             for i, request in enumerate(requests):
  1048.                 thread = HTTPDownloader(i, request, start,
  1049.                                         self.config['length']['download'])
  1050.                 thread.start()
  1051.                 q.put(thread, True)
  1052.                 callback(i, request_count, start=True)
  1053.  
  1054.         finished = []
  1055.  
  1056.         def consumer(q, request_count):
  1057.             while len(finished) < request_count:
  1058.                 thread = q.get(True)
  1059.                 while thread.isAlive():
  1060.                     thread.join(timeout=0.1)
  1061.                 finished.append(sum(thread.result))
  1062.                 callback(thread.i, request_count, end=True)
  1063.  
  1064.         q = Queue(self.config['threads']['download'])
  1065.         prod_thread = threading.Thread(target=producer,
  1066.                                        args=(q, requests, request_count))
  1067.         cons_thread = threading.Thread(target=consumer,
  1068.                                        args=(q, request_count))
  1069.         start = timeit.default_timer()
  1070.         prod_thread.start()
  1071.         cons_thread.start()
  1072.         while prod_thread.isAlive():
  1073.             prod_thread.join(timeout=0.1)
  1074.         while cons_thread.isAlive():
  1075.             cons_thread.join(timeout=0.1)
  1076.  
  1077.         stop = timeit.default_timer()
  1078.         self.results.bytes_received = sum(finished)
  1079.         self.results.download = (
  1080.             (self.results.bytes_received / (stop - start)) * 8.0
  1081.         )
  1082.         if self.results.download > 100000:
  1083.             self.config['threads']['upload'] = 8
  1084.         return self.results.download
  1085.  
  1086.     def upload(self, callback=do_nothing):
  1087.         """Test upload speed against speedtest.net"""
  1088.  
  1089.         sizes = []
  1090.  
  1091.         for size in self.config['sizes']['upload']:
  1092.             for _ in range(0, self.config['counts']['upload']):
  1093.                 sizes.append(size)
  1094.  
  1095.         # request_count = len(sizes)
  1096.         request_count = self.config['upload_max']
  1097.  
  1098.         requests = []
  1099.         for i, size in enumerate(sizes):
  1100.             # We set ``0`` for ``start`` and handle setting the actual
  1101.             # ``start`` in ``HTTPUploader`` to get better measurements
  1102.             requests.append(
  1103.                 (
  1104.                     build_request(
  1105.                         self.best['url'],
  1106.                         HTTPUploaderData(size, 0,
  1107.                                          self.config['length']['upload'])
  1108.                     ),
  1109.                     size
  1110.                 )
  1111.             )
  1112.  
  1113.         def producer(q, requests, request_count):
  1114.             for i, request in enumerate(requests[:request_count]):
  1115.                 thread = HTTPUploader(i, request[0], start, request[1],
  1116.                                       self.config['length']['upload'])
  1117.                 thread.start()
  1118.                 q.put(thread, True)
  1119.                 callback(i, request_count, start=True)
  1120.  
  1121.         finished = []
  1122.  
  1123.         def consumer(q, request_count):
  1124.             while len(finished) < request_count:
  1125.                 thread = q.get(True)
  1126.                 while thread.isAlive():
  1127.                     thread.join(timeout=0.1)
  1128.                 finished.append(thread.result)
  1129.                 callback(thread.i, request_count, end=True)
  1130.  
  1131.         q = Queue(self.config['threads']['upload'])
  1132.         prod_thread = threading.Thread(target=producer,
  1133.                                        args=(q, requests, request_count))
  1134.         cons_thread = threading.Thread(target=consumer,
  1135.                                        args=(q, request_count))
  1136.         start = timeit.default_timer()
  1137.         prod_thread.start()
  1138.         cons_thread.start()
  1139.         while prod_thread.isAlive():
  1140.             prod_thread.join(timeout=0.1)
  1141.         while cons_thread.isAlive():
  1142.             cons_thread.join(timeout=0.1)
  1143.  
  1144.         stop = timeit.default_timer()
  1145.         self.results.bytes_sent = sum(finished)
  1146.         self.results.upload = (
  1147.             (self.results.bytes_sent / (stop - start)) * 8.0
  1148.         )
  1149.         return self.results.upload
  1150.  
  1151.  
  1152. def ctrl_c(signum, frame):
  1153.     """Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
  1154.    operations
  1155.    """
  1156.  
  1157.     SHUTDOWN_EVENT.set()
  1158.     print_('\nCancelling...')
  1159.     sys.exit(0)
  1160.  
  1161.  
  1162. def version():
  1163.     """Print the version"""
  1164.  
  1165.     print_(__version__)
  1166.     sys.exit(0)
  1167.  
  1168.  
  1169. def csv_header():
  1170.     """Print the CSV Headers"""
  1171.  
  1172.     print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,'
  1173.            'Upload')
  1174.     sys.exit(0)
  1175.  
  1176.  
  1177. def parse_args():
  1178.     """Function to handle building and parsing of command line arguments"""
  1179.     description = (
  1180.         'Command line interface for testing internet bandwidth using '
  1181.         'speedtest.net.\n'
  1182.         '------------------------------------------------------------'
  1183.         '--------------\n'
  1184.         'https://github.com/sivel/speedtest-cli')
  1185.  
  1186.     parser = ArgParser(description=description)
  1187.     # Give optparse.OptionParser an `add_argument` method for
  1188.     # compatibility with argparse.ArgumentParser
  1189.     try:
  1190.         parser.add_argument = parser.add_option
  1191.     except AttributeError:
  1192.         pass
  1193.     parser.add_argument('--bytes', dest='units', action='store_const',
  1194.                         const=('byte', 8), default=('bit', 1),
  1195.                         help='Display values in bytes instead of bits. Does '
  1196.                              'not affect the image generated by --share, nor '
  1197.                              'output from --json or --csv')
  1198.     parser.add_argument('--share', action='store_true',
  1199.                         help='Generate and provide a URL to the speedtest.net '
  1200.                              'share results image')
  1201.     parser.add_argument('--simple', action='store_true', default=False,
  1202.                         help='Suppress verbose output, only show basic '
  1203.                              'information')
  1204.     parser.add_argument('--csv', action='store_true', default=False,
  1205.                         help='Suppress verbose output, only show basic '
  1206.                              'information in CSV format. Speeds listed in '
  1207.                              'bit/s and not affected by --bytes')
  1208.     parser.add_argument('--csv-delimiter', default=',', type=PARSER_TYPE_STR,
  1209.                         help='Single character delimiter to use in CSV '
  1210.                              'output. Default ","')
  1211.     parser.add_argument('--csv-header', action='store_true', default=False,
  1212.                         help='Print CSV headers')
  1213.     parser.add_argument('--json', action='store_true', default=False,
  1214.                         help='Suppress verbose output, only show basic '
  1215.                              'information in JSON format. Speeds listed in '
  1216.                              'bit/s and not affected by --bytes')
  1217.     parser.add_argument('--list', action='store_true',
  1218.                         help='Display a list of speedtest.net servers '
  1219.                              'sorted by distance')
  1220.     parser.add_argument('--server', help='Specify a server ID to test against',
  1221.                         type=PARSER_TYPE_INT)
  1222.     parser.add_argument('--mini', help='URL of the Speedtest Mini server')
  1223.     parser.add_argument('--source', help='Source IP address to bind to')
  1224.     parser.add_argument('--timeout', default=10, type=PARSER_TYPE_INT,
  1225.                         help='HTTP timeout in seconds. Default 10')
  1226.     parser.add_argument('--secure', action='store_true',
  1227.                         help='Use HTTPS instead of HTTP when communicating '
  1228.                              'with speedtest.net operated servers')
  1229.     parser.add_argument('--version', action='store_true',
  1230.                         help='Show the version number and exit')
  1231.     parser.add_argument('--debug', action='store_true',
  1232.                         help=ARG_SUPPRESS, default=ARG_SUPPRESS)
  1233.  
  1234.     options = parser.parse_args()
  1235.     if isinstance(options, tuple):
  1236.         args = options[0]
  1237.     else:
  1238.         args = options
  1239.     return args
  1240.  
  1241.  
  1242. def validate_optional_args(args):
  1243.     """Check if an argument was provided that depends on a module that may
  1244.    not be part of the Python standard library.
  1245.  
  1246.    If such an argument is supplied, and the module does not exist, exit
  1247.    with an error stating which module is missing.
  1248.    """
  1249.     optional_args = {
  1250.         'json': ('json/simplejson python module', json),
  1251.         'secure': ('SSL support', HTTPSConnection),
  1252.     }
  1253.  
  1254.     for arg, info in optional_args.items():
  1255.         if getattr(args, arg, False) and info[1] is None:
  1256.             raise SystemExit('%s is not installed. --%s is '
  1257.                              'unavailable' % (info[0], arg))
  1258.  
  1259.  
  1260. def printer(string, quiet=False, debug=False, **kwargs):
  1261.     """Helper function to print a string only when not quiet"""
  1262.  
  1263.     if debug and not DEBUG:
  1264.         return
  1265.  
  1266.     if debug:
  1267.         out = '\033[1;30mDEBUG: %s\033[0m' % string
  1268.     else:
  1269.         out = string
  1270.  
  1271.     if not quiet:
  1272.         print_(out, **kwargs)
  1273.  
  1274.  
  1275. def shell():
  1276.     """Run the full speedtest.net test"""
  1277.  
  1278.     global SHUTDOWN_EVENT, SOURCE, SCHEME, DEBUG
  1279.     SHUTDOWN_EVENT = threading.Event()
  1280.  
  1281.     signal.signal(signal.SIGINT, ctrl_c)
  1282.  
  1283.     args = parse_args()
  1284.  
  1285.     # Print the version and exit
  1286.     if args.version:
  1287.         version()
  1288.  
  1289.     if args.csv_header:
  1290.         csv_header()
  1291.  
  1292.     if len(args.csv_delimiter) != 1:
  1293.         raise SystemExit('--csv-delimiter must be a single character')
  1294.  
  1295.     validate_optional_args(args)
  1296.  
  1297.     socket.setdefaulttimeout(args.timeout)
  1298.  
  1299.     # If specified bind to a specific IP address
  1300.     if args.source:
  1301.         SOURCE = args.source
  1302.         socket.socket = bound_socket
  1303.  
  1304.     if args.secure:
  1305.         SCHEME = 'https'
  1306.  
  1307.     debug = getattr(args, 'debug', False)
  1308.     if debug == 'SUPPRESSHELP':
  1309.         debug = False
  1310.     if debug:
  1311.         DEBUG = True
  1312.  
  1313.     # Pre-cache the user agent string
  1314.     build_user_agent()
  1315.  
  1316.     if args.simple or args.csv or args.json:
  1317.         quiet = True
  1318.     else:
  1319.         quiet = False
  1320.  
  1321.     # Don't set a callback if we are running quietly
  1322.    if quiet or debug:
  1323.        callback = do_nothing
  1324.    else:
  1325.        callback = print_dots
  1326.  
  1327.    printer('Retrieving speedtest.net configuration...', quiet)
  1328.    try:
  1329.        speedtest = Speedtest()
  1330.    except (ConfigRetrievalError, HTTP_ERRORS):
  1331.        printer('Cannot retrieve speedtest configuration')
  1332.        raise SpeedtestCLIError(get_exception())
  1333.  
  1334.    if args.list:
  1335.        try:
  1336.            speedtest.get_servers()
  1337.        except (ServersRetrievalError, HTTP_ERRORS):
  1338.            print_('Cannot retrieve speedtest server list')
  1339.            raise SpeedtestCLIError(get_exception())
  1340.  
  1341.        for _, servers in sorted(speedtest.servers.items()):
  1342.            for server in servers:
  1343.                line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) '
  1344.                        '[%(d)0.2f km]' % server)
  1345.                try:
  1346.                    print_(line)
  1347.                except IOError:
  1348.                    e = get_exception()
  1349.                    if e.errno != errno.EPIPE:
  1350.                        raise
  1351.        sys.exit(0)
  1352.  
  1353.    # Set a filter of servers to retrieve
  1354.    servers = []
  1355.    if args.server:
  1356.        servers.append(args.server)
  1357.  
  1358.    printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'],
  1359.            quiet)
  1360.  
  1361.    if not args.mini:
  1362.        printer('Retrieving speedtest.net server list...', quiet)
  1363.        try:
  1364.            speedtest.get_servers(servers)
  1365.        except NoMatchedServers:
  1366.            raise SpeedtestCLIError('No matched servers: %s' % args.server)
  1367.        except (ServersRetrievalError, HTTP_ERRORS):
  1368.            print_('Cannot retrieve speedtest server list')
  1369.            raise SpeedtestCLIError(get_exception())
  1370.        except InvalidServerIDType:
  1371.            raise SpeedtestCLIError('%s is an invalid server type, must '
  1372.                                    'be an int' % args.server)
  1373.  
  1374.        printer('Selecting best server based on ping...', quiet)
  1375.        speedtest.get_best_server()
  1376.    elif args.mini:
  1377.        speedtest.get_best_server(speedtest.set_mini_server(args.mini))
  1378.  
  1379.    results = speedtest.results
  1380.  
  1381.    printer('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '
  1382.            '%(latency)s ms' % results.server, quiet)
  1383.  
  1384.    printer('Testing download speed', quiet,
  1385.            end=('', '\n')[bool(debug)])
  1386.    speedtest.download(callback=callback)
  1387.    printer('Download: %0.2f M%s/s' %
  1388.            ((results.download / 1000.0 / 1000.0) / args.units[1],
  1389.             args.units[0]),
  1390.            quiet)
  1391.  
  1392.    printer('Testing upload speed', quiet,
  1393.            end=('', '\n')[bool(debug)])
  1394.    speedtest.upload(callback=callback)
  1395.    printer('Upload: %0.2f M%s/s' %
  1396.            ((results.upload / 1000.0 / 1000.0) / args.units[1],
  1397.             args.units[0]),
  1398.            quiet)
  1399.  
  1400.    if args.simple:
  1401.        print_('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' %
  1402.               (results.ping,
  1403.                (results.download / 1000.0 / 1000.0) / args.units[1],
  1404.                args.units[0],
  1405.                (results.upload / 1000.0 / 1000.0) / args.units[1],
  1406.                args.units[0]))
  1407.    elif args.csv:
  1408.        print_(results.csv(delimiter=args.csv_delimiter))
  1409.    elif args.json:
  1410.        print_(results.json())
  1411.  
  1412.    if args.share:
  1413.        printer('Share results: %s' % results.share(), quiet)
  1414.  
  1415.  
  1416. def main():
  1417.    try:
  1418.        shell()
  1419.    except KeyboardInterrupt:
  1420.        print_('\nCancelling...')
  1421.    except (SpeedtestException, SystemExit):
  1422.        e = get_exception()
  1423.        if getattr(e, 'code', 1) != 0:
  1424.            raise SystemExit('ERROR: %s' % e)
  1425.  
  1426.  
  1427. if __name__ == '__main__':
  1428.    main()
  1429.  
  1430. # vim:ts=4:sw=4:expandtab
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement