Python distutils.version() Examples

The following are 30 code examples of distutils.version(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module distutils , or try the search function .
Example #1
Source File: versionpredicate.py    From meddle with MIT License 6 votes vote down vote up
def split_provision(value):
    """Return the name and optional version number of a provision.

    The version number, if given, will be returned as a `StrictVersion`
    instance, otherwise it will be `None`.

    >>> split_provision('mypkg')
    ('mypkg', None)
    >>> split_provision(' mypkg( 1.2 ) ')
    ('mypkg', StrictVersion ('1.2'))
    """
    global _provision_rx
    if _provision_rx is None:
        _provision_rx = re.compile(
            "([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$")
    value = value.strip()
    m = _provision_rx.match(value)
    if not m:
        raise ValueError("illegal provides specification: %r" % value)
    ver = m.group(2) or None
    if ver:
        ver = distutils.version.StrictVersion(ver)
    return m.group(1), ver 
Example #2
Source File: versionpredicate.py    From oss-ftp with MIT License 6 votes vote down vote up
def split_provision(value):
    """Return the name and optional version number of a provision.

    The version number, if given, will be returned as a `StrictVersion`
    instance, otherwise it will be `None`.

    >>> split_provision('mypkg')
    ('mypkg', None)
    >>> split_provision(' mypkg( 1.2 ) ')
    ('mypkg', StrictVersion ('1.2'))
    """
    global _provision_rx
    if _provision_rx is None:
        _provision_rx = re.compile(
            "([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$")
    value = value.strip()
    m = _provision_rx.match(value)
    if not m:
        raise ValueError("illegal provides specification: %r" % value)
    ver = m.group(2) or None
    if ver:
        ver = distutils.version.StrictVersion(ver)
    return m.group(1), ver 
Example #3
Source File: test_imagefont.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version)

        self.metrics = self.METRICS['Default']
        for conditions, metrics in self.METRICS.items():
            if not isinstance(conditions, tuple):
                continue

            for condition in conditions:
                version = re.sub('[<=>]', '', condition)
                if (condition.startswith('>=') and freetype >= version) or \
                   (condition.startswith('<') and freetype < version):
                    # Condition was met
                    continue

                # Condition failed
                break
            else:
                # All conditions were met
                self.metrics = metrics 
Example #4
Source File: __init__.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def checkdep_ghostscript():
    if checkdep_ghostscript.executable is None:
        if sys.platform == 'win32':
            # mgs is the name in miktex
            gs_execs = ['gswin32c', 'gswin64c', 'mgs', 'gs']
        else:
            gs_execs = ['gs']
        for gs_exec in gs_execs:
            try:
                s = subprocess.Popen(
                    [gs_exec, '--version'], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
                stdout, stderr = s.communicate()
                if s.returncode == 0:
                    v = stdout[:-1].decode('ascii')
                    checkdep_ghostscript.executable = gs_exec
                    checkdep_ghostscript.version = v
            except (IndexError, ValueError, OSError):
                pass
    return checkdep_ghostscript.executable, checkdep_ghostscript.version 
Example #5
Source File: __init__.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def checkdep_ghostscript():
    if sys.platform == 'win32':
        gs_execs = ['gswin32c', 'gswin64c', 'gs']
    else:
        gs_execs = ['gs']
    for gs_exec in gs_execs:
        try:
            s = subprocess.Popen(
                [gs_exec, '--version'], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            stdout, stderr = s.communicate()
            if s.returncode == 0:
                v = byte2str(stdout[:-1])
                return gs_exec, v
        except (IndexError, ValueError, OSError):
            pass
    return None, None 
Example #6
Source File: __init__.py    From gym-pull with MIT License 6 votes vote down vote up
def sanity_check_dependencies():
    import numpy
    import requests
    import six

    if distutils.version.LooseVersion(numpy.__version__) < distutils.version.LooseVersion('1.10.4'):
        logger.warn("You have 'numpy' version %s installed, but 'gym' requires at least 1.10.4. HINT: upgrade via 'pip install -U numpy'.", numpy.__version__)

    if distutils.version.LooseVersion(requests.__version__) < distutils.version.LooseVersion('2.0'):
        logger.warn("You have 'requests' version %s installed, but 'gym' requires at least 2.0. HINT: upgrade via 'pip install -U requests'.", requests.__version__)

# We automatically configure a logger with a simple stderr handler. If
# you'd rather customize logging yourself, run undo_logger_setup.
#
# (Note: this needs to happen before importing the rest of gym, since
# we may print a warning at load time.) 
Example #7
Source File: __init__.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compare_versions(a, b):
    "return True if a is greater than or equal to b"
    if isinstance(a, bytes):
        cbook.warn_deprecated(
            "3.0", "compare_version arguments should be strs.")
        a = a.decode('ascii')
    if isinstance(b, bytes):
        cbook.warn_deprecated(
            "3.0", "compare_version arguments should be strs.")
        b = b.decode('ascii')
    if a:
        a = distutils.version.LooseVersion(a)
        b = distutils.version.LooseVersion(b)
        return a >= b
    else:
        return False 
Example #8
Source File: __init__.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def checkdep_inkscape():
    if checkdep_inkscape.version is None:
        try:
            s = subprocess.Popen(['inkscape', '-V'],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = s.communicate()
            lines = stdout.decode('ascii').split('\n')
            for line in lines:
                if 'Inkscape' in line:
                    v = line.split()[1]
                    break
            checkdep_inkscape.version = v
        except (IndexError, ValueError, UnboundLocalError, OSError):
            pass
    return checkdep_inkscape.version 
Example #9
Source File: __init__.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", "{} is deprecated; in the future, examples will be "
                "found relative to the 'datapath' directory.".format(key))

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example #10
Source File: versionpredicate.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def split_provision(value):
    """Return the name and optional version number of a provision.

    The version number, if given, will be returned as a `StrictVersion`
    instance, otherwise it will be `None`.

    >>> split_provision('mypkg')
    ('mypkg', None)
    >>> split_provision(' mypkg( 1.2 ) ')
    ('mypkg', StrictVersion ('1.2'))
    """
    global _provision_rx
    if _provision_rx is None:
        _provision_rx = re.compile(
            "([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$")
    value = value.strip()
    m = _provision_rx.match(value)
    if not m:
        raise ValueError("illegal provides specification: %r" % value)
    ver = m.group(2) or None
    if ver:
        ver = distutils.version.StrictVersion(ver)
    return m.group(1), ver 
Example #11
Source File: __init__.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def checkdep_inkscape():
    if checkdep_inkscape.version is None:
        try:
            s = subprocess.Popen(['inkscape', '-V'],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = s.communicate()
            lines = stdout.decode('ascii').split('\n')
            for line in lines:
                if 'Inkscape' in line:
                    v = line.split()[1]
                    break
            checkdep_inkscape.version = v
        except (IndexError, ValueError, UnboundLocalError, OSError):
            pass
    return checkdep_inkscape.version 
Example #12
Source File: nwbextractors.py    From spikeextractors with MIT License 6 votes vote down vote up
def get_traces(self, channel_ids=None, start_frame=None, end_frame=None):
        with NWBHDF5IO(self._path, 'r') as io:
            nwbfile = io.read()
            es = nwbfile.acquisition[self._electrical_series_name]
            es_channel_ids = np.array(es.electrodes.table.id[:])[es.electrodes.data[:]].tolist()
            table_ids = [es_channel_ids.index(id) for id in channel_ids]
            if np.array(channel_ids).size > 1 and np.any(np.diff(channel_ids) < 0):
                sorted_idx = np.argsort(table_ids)
                recordings = es.data[start_frame:end_frame, np.sort(table_ids)].T
                traces = recordings[sorted_idx, :]
            else:
                traces = es.data[start_frame:end_frame, table_ids].T
            # This DatasetView and lazy operations will only work within context
            # We're keeping the non-lazy version for now
            # es_view = DatasetView(es.data)  # es is an instantiated h5py dataset
            # traces = es_view.lazy_slice[start_frame:end_frame, channel_ids].lazy_transpose()
        return traces 
Example #13
Source File: __init__.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def checkdep_ghostscript():
    if checkdep_ghostscript.executable is None:
        if sys.platform == 'win32':
            # mgs is the name in miktex
            gs_execs = ['gswin32c', 'gswin64c', 'mgs', 'gs']
        else:
            gs_execs = ['gs']
        for gs_exec in gs_execs:
            try:
                s = subprocess.Popen(
                    [gs_exec, '--version'], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
                stdout, stderr = s.communicate()
                if s.returncode == 0:
                    v = stdout[:-1].decode('ascii')
                    checkdep_ghostscript.executable = gs_exec
                    checkdep_ghostscript.version = v
            except (IndexError, ValueError, OSError):
                pass
    return checkdep_ghostscript.executable, checkdep_ghostscript.version 
Example #14
Source File: __init__.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def compare_versions(a, b):
    "return True if a is greater than or equal to b"
    if isinstance(a, bytes):
        cbook.warn_deprecated(
            "3.0", "compare_version arguments should be strs.")
        a = a.decode('ascii')
    if isinstance(b, bytes):
        cbook.warn_deprecated(
            "3.0", "compare_version arguments should be strs.")
        b = b.decode('ascii')
    if a:
        a = distutils.version.LooseVersion(a)
        b = distutils.version.LooseVersion(b)
        return a >= b
    else:
        return False 
Example #15
Source File: texmanager.py    From neural-network-animation with MIT License 6 votes vote down vote up
def dvipng_hack_alpha():
    try:
        p = Popen(['dvipng', '-version'], stdin=PIPE, stdout=PIPE,
                  stderr=STDOUT, close_fds=(sys.platform != 'win32'))
        stdout, stderr = p.communicate()
    except OSError:
        mpl.verbose.report('No dvipng was found', 'helpful')
        return False
    lines = stdout.decode('ascii').split('\n')
    for line in lines:
        if line.startswith('dvipng '):
            version = line.split()[-1]
            mpl.verbose.report('Found dvipng version %s' % version,
                               'helpful')
            version = distutils.version.LooseVersion(version)
            return version < distutils.version.LooseVersion('1.6')
    mpl.verbose.report('Unexpected response from dvipng -version', 'helpful')
    return False 
Example #16
Source File: dataio.py    From tridesclous with MIT License 6 votes vote down vote up
def _check_tridesclous_version(self):
        folder_version= self.info.get('tridesclous_version', 'unknown')
        
        if folder_version is 'unknown':
            w = True
        else:
            v1 = distutils.version.LooseVersion(tridesclous_version).version
            v2 = distutils.version.LooseVersion(self.info['tridesclous_version']).version
            if (v1[0] == v2[0]) and (v1[1] == v2[1]):
                w = False
            else:
                w = True

        if w:
            txt = 'This folder was created with an old tridesclous version ({})\n'\
                    'The actual version is {}\n'\
                    'You may have bug in internal structure.'
            print(txt.format(folder_version, tridesclous_version)) 
Example #17
Source File: versionpredicate.py    From BinderFilter with MIT License 6 votes vote down vote up
def split_provision(value):
    """Return the name and optional version number of a provision.

    The version number, if given, will be returned as a `StrictVersion`
    instance, otherwise it will be `None`.

    >>> split_provision('mypkg')
    ('mypkg', None)
    >>> split_provision(' mypkg( 1.2 ) ')
    ('mypkg', StrictVersion ('1.2'))
    """
    global _provision_rx
    if _provision_rx is None:
        _provision_rx = re.compile(
            "([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$")
    value = value.strip()
    m = _provision_rx.match(value)
    if not m:
        raise ValueError("illegal provides specification: %r" % value)
    ver = m.group(2) or None
    if ver:
        ver = distutils.version.StrictVersion(ver)
    return m.group(1), ver 
Example #18
Source File: __init__.py    From Computable with MIT License 6 votes vote down vote up
def checkdep_ghostscript():
    if sys.platform == 'win32':
        gs_execs = ['gswin32c', 'gswin64c', 'gs']
    else:
        gs_execs = ['gs']
    for gs_exec in gs_execs:
        try:
            s = subprocess.Popen(
                [gs_exec, '--version'], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            stdout, stderr = s.communicate()
            if s.returncode == 0:
                v = byte2str(stdout[:-1])
                return gs_exec, v
        except (IndexError, ValueError, OSError):
            pass
    return None, None 
Example #19
Source File: __init__.py    From neural-network-animation with MIT License 6 votes vote down vote up
def checkdep_ghostscript():
    if sys.platform == 'win32':
        gs_execs = ['gswin32c', 'gswin64c', 'gs']
    else:
        gs_execs = ['gs']
    for gs_exec in gs_execs:
        try:
            s = subprocess.Popen(
                [gs_exec, '--version'], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            stdout, stderr = s.communicate()
            if s.returncode == 0:
                v = stdout[:-1].decode('ascii')
                return gs_exec, v
        except (IndexError, ValueError, OSError):
            pass
    return None, None 
Example #20
Source File: util_cplat_packages.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def version_ge(version1, version2):
    """
    >>> from util_cplat_packages import *
    >>> version1 = distro_version
    >>> version2 = '15.03'
    """
    import distutils.version
    flag = distutils.version.LooseVersion(version1) >= distutils.version.LooseVersion(version2)
    return flag


# PRINT WHAT WE ARE WORKING WITH 
Example #21
Source File: utils.py    From parasol with MIT License 5 votes vote down vote up
def version_info(self):
        return {
            'backend':self.backend,
            'version':str(subprocess.check_output([self.backend, '-version'],
                                                  stderr=subprocess.STDOUT)),
            'cmdline':self.cmdline
        } 
Example #22
Source File: __init__.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def checkdep_pdftops():
    try:
        s = subprocess.Popen(['pdftops','-v'], stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        for line in s.stderr:
            if b'version' in line:
                v = byte2str(line.split()[-1])
        return v
    except (IndexError, ValueError, UnboundLocalError, OSError):
        return None 
Example #23
Source File: utils.py    From parasol with MIT License 5 votes vote down vote up
def capture_frame(self, frame):
        if not isinstance(frame, (np.ndarray, np.generic)):
            raise error.InvalidFrame('Wrong type {} for {} (must be np.ndarray or np.generic)'.format(type(frame), frame))
        if frame.shape != self.frame_shape:
            raise error.InvalidFrame("Your frame has shape {}, but the VideoRecorder is configured for shape {}.".format(frame.shape, self.frame_shape))
        if frame.dtype != np.uint8:
            raise error.InvalidFrame("Your frame has data type {}, but we require uint8 (i.e. RGB values from 0-255).".format(frame.dtype))

        if distutils.version.LooseVersion(np.__version__) >= distutils.version.LooseVersion('1.9.0'):
            self.proc.stdin.write(frame.tobytes())
        else:
            self.proc.stdin.write(frame.tostring()) 
Example #24
Source File: utils.py    From parasol with MIT License 5 votes vote down vote up
def close(self):
        #frame_duration = float(1) / self.frames_per_sec
        frame_duration = .5

        # Turn frames into events: clear screen beforehand
        # https://rosettacode.org/wiki/Terminal_control/Clear_the_screen#Python
        # https://rosettacode.org/wiki/Terminal_control/Cursor_positioning#Python
        clear_code = six.b("%c[2J\033[1;1H" % (27))
        # Decode the bytes as UTF-8 since JSON may only contain UTF-8
        events = [ (frame_duration, (clear_code+frame.replace(six.b('\n'),six.b('\r\n'))).decode('utf-8'))  for frame in self.frames ]

        # Calculate frame size from the largest frames.
        # Add some padding since we'll get cut off otherwise.
        height = max([frame.count(six.b('\n')) for frame in self.frames]) + 1
        width = max([max([len(line) for line in frame.split(six.b('\n'))]) for frame in self.frames]) + 2

        data = {
            "version": 1,
            "width": width,
            "height": height,
            "duration": len(self.frames)*frame_duration,
            "command": "-",
            "title": "gym VideoRecorder episode",
            "env": {}, # could add some env metadata here
            "stdout": events,
        }

        with open(self.output_path, 'w') as f:
            json.dump(data, f) 
Example #25
Source File: __init__.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_py2exe_datafiles():
    datapath = get_data_path()
    _, tail = os.path.split(datapath)
    d = {}
    for root, _, files in os.walk(datapath):
        # Need to explicitly remove cocoa_agg files or py2exe complains
        # NOTE I dont know why, but do as previous version
        if 'Matplotlib.nib' in files:
            files.remove('Matplotlib.nib')
        files = [os.path.join(root, filename) for filename in files]
        root = root.replace(tail, 'mpl-data')
        root = root[root.index('mpl-data'):]
        d[root] = files
    return list(d.items()) 
Example #26
Source File: __init__.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def checkdep_ps_distiller(s):
    if not s:
        return False

    flag = True
    gs_req = '7.07'
    gs_sugg = '7.07'
    gs_exec, gs_v = checkdep_ghostscript()
    if compare_versions(gs_v, gs_sugg): pass
    elif compare_versions(gs_v, gs_req):
        verbose.report(('ghostscript-%s found. ghostscript-%s or later '
                        'is recommended to use the ps.usedistiller option.') % (gs_v, gs_sugg))
    else:
        flag = False
        warnings.warn(('matplotlibrc ps.usedistiller option can not be used '
                       'unless ghostscript-%s or later is installed on your system') % gs_req)

    if s == 'xpdf':
        pdftops_req = '3.0'
        pdftops_req_alt = '0.9' # poppler version numbers, ugh
        pdftops_v = checkdep_pdftops()
        if compare_versions(pdftops_v, pdftops_req):
            pass
        elif compare_versions(pdftops_v, pdftops_req_alt) and not \
            compare_versions(pdftops_v, '1.0'):
            pass
        else:
            flag = False
            warnings.warn(('matplotlibrc ps.usedistiller can not be set to '
                           'xpdf unless xpdf-%s or later is installed on your system') % pdftops_req)

    if flag:
        return s
    else:
        return False 
Example #27
Source File: __init__.py    From neural-network-animation with MIT License 5 votes vote down vote up
def compare_versions(a, b):
    "return True if a is greater than or equal to b"
    if a:
        if six.PY3:
            if isinstance(a, bytes):
                a = a.decode('ascii')
            if isinstance(b, bytes):
                b = b.decode('ascii')
        a = distutils.version.LooseVersion(a)
        b = distutils.version.LooseVersion(b)
        return a >= b
    else:
        return False 
Example #28
Source File: __init__.py    From neural-network-animation with MIT License 5 votes vote down vote up
def checkdep_dvipng():
    try:
        s = subprocess.Popen(['dvipng','-version'], stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = s.communicate()
        line = stdout.decode('ascii').split('\n')[1]
        v = line.split()[-1]
        return v
    except (IndexError, ValueError, OSError):
        return None 
Example #29
Source File: __init__.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def compare_versions(a, b):
    "return True if a is greater than or equal to b"
    if a:
        a = distutils.version.LooseVersion(a)
        b = distutils.version.LooseVersion(b)
        if a>=b: return True
        else: return False
    else: return False 
Example #30
Source File: utils.py    From parasol with MIT License 5 votes vote down vote up
def version_info(self):
        return {'backend':'TextEncoder','version':1}