我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.version()。
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
def _increment_version(self, version, kind): if kind == 'patch': major, minor, patch = self.version new_version = (major, minor, patch + 1) elif kind == 'minor': major, minor, patch = self.version new_version = (major, minor + 1, 0) elif kind == 'major': major, minor, patch = self.version new_version = (major + 1, 0, 0) elif kind is None: new_version = self.version else: raise ValueError('Bump kind "{}" not understood'.format(kind)) return new_version
def load_transformers(name, config): transformers = [] for version, names in six.iteritems(config): extension_manager = stevedore.ExtensionManager( 'nailgun.cluster_upgrade.transformations.{}.{}'.format( name, version), on_load_failure_callback=reraise_endpoint_load_failure, ) try: sorted_extensions = [extension_manager[n].plugin for n in names] except KeyError as exc: LOG.error('%s transformer %s not found for version %s', name, exc, version) raise strict_version = distutils.version.StrictVersion(version) transformers.append((strict_version, sorted_extensions)) transformers.sort() return transformers
def apply(self, from_version, to_version, data): strict_from = distutils.version.StrictVersion(from_version) strict_to = distutils.version.StrictVersion(to_version) assert strict_from <= strict_to, \ "from_version must not be greater than to_version" data = copy.deepcopy(data) for version, transformers in self.transformers: if version <= strict_from: continue if version > strict_to: break for transformer in transformers: LOG.debug("Applying %s transformer %s", self.name, transformer) data = transformer(data) return data
def _find_prefix(filename): """ In virtualenv, _CONFIG_H and _MAKEFILE may have same or different prefixes, depending on the version of virtualenv. Try to find the correct one, which is assumed to be the longest one. """ if not is_venv: return sys.prefix filename = os.path.abspath(filename) prefixes = [os.path.abspath(sys.prefix), base_prefix] possible_prefixes = [] for prefix in prefixes: common = os.path.commonprefix([prefix, filename]) if common == prefix: possible_prefixes.append(prefix) possible_prefixes.sort(key=lambda p: len(p), reverse=True) return possible_prefixes[0]
def _get_template_kin(dapver, template_kin=None): """Checks the template_kin and returns the default value if None.""" if template_kin is not None: template_kin = template_kin.upper() templates_check = __TEMPLATES_KIN_MPL4__ if _is_MPL4(dapver) else __TEMPLATES_KIN__ assert template_kin in templates_check, ('invalid template_kin. ' 'template_kin must be one of {0}' .format(templates_check)) return template_kin # Defines the default value depending on the version if _is_MPL4(dapver): return __TEMPLATES_KIN_MPL4_DEFAULT__ else: return __TEMPLATES_KIN_DEFAULT__
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.)
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*\))?$", re.ASCII) 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
def addOrGetBucket(buckets, rules): ruleHash = None if rules: ruleHash = hash(json.dumps(rules.to_json())) bucket = None if ruleHash in buckets: bucket = buckets[ruleHash] else: bucket = MultiMCVersionFile( { "name": "LWJGL", "version": "undetermined", "uid": "org.lwjgl" } ) bucket.type = "release" buckets[ruleHash] = bucket return bucket
def isOnlyMacOS(rules, specifier): allowsOSX = False allowsAll = False #print("Considering", specifier, "rules", rules) if rules: for rule in rules: if rule.action == "allow" and rule.os and rule.os.name == "osx": allowsOSX = True if rule.action == "allow" and not rule.os: allowsAll = True if allowsOSX and not allowsAll: return True return False # get the local version list
def get_latest_version(release_information): """Iterate over object and return the latest version, as defined by distutils.version.StrictVersion. The argument is intended to be a dictionary with versions as key, but anything outputing version strings will work.""" latest = None latest_strict = None # might contain '-' replaced through '.' for version in release_information: version_strict = version[:] if '-' in version_strict: version_strict = version_strict.replace('-', '.') try: version_strict = distutils.version.StrictVersion(version_strict) except ValueError as e: raise ReleaseError(e.args) if not latest: latest = version latest_strict = version_strict else: if version_strict > latest_strict: latest = version latest_strict = version_strict if not latest: raise ReleaseError("No versions found for " % repr(release_information)) return latest
def extract_version(string): """Try to extract a version from the given string and feed it into distutils.version.StrictVersion, which is returned. If no version could be extracted, a ValueError is raised. If the given parameter is a path, only the last chunk, "base name", is used.""" if os.sep in string: # it's a path string = os.path.basename(string.rstrip(os.sep)) match = config.VERSION_PATTERN.search(string) if not match: raise ValueError("%s doesn't contain a version number to extract" % string) # remove None groups and join the fragments together with a dot to make # StrictVersion happy match = ''.join([m for m in match.groups() if m is not None]) if match.endswith('.'): # strip trailing dots match = match.rstrip('.').lstrip('.') return distutils.version.LooseVersion(match)
def text_to_phonemes(s, *, ipa=False): ''' translate text to phonemes ''' s = s.encode('UTF-8') z = ctypes.c_char_p(s) zptr = ctypes.pointer(z) assert zptr.contents is not None if version >= '1.48.11': ipa = ipa << 1 # no coverage else: ipa = ipa << 4 res = _text_to_phonemes(zptr, 1, ipa) if zptr.contents.value is not None: raise RuntimeError # no coverage return res.decode('UTF-8').strip()
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())
def release(version, github_access_token): repo = 'nriley/LBOfficeMRU' os.chdir(project_path()) action_paths = glob.glob('*.lbaction') for action_path in action_paths: # update version number and download URL in the working copy so it can be committed update_bundle_version(action_path, version, repo) archive_path = archive_bundles('LBOfficeMRU', version, action_paths) if github_access_token is None: return html_url = upload_release('nriley/LBOfficeMRU', version, archive_path, github_access_token) webbrowser.open(html_url)
def splitUp(pred): """Parse a single version comparison. Return (comparison string, StrictVersion) """ res = re_splitComparison.match(pred) if not res: raise ValueError("bad package restriction syntax: %r" % pred) comp, verStr = res.groups() return (comp, distutils.version.StrictVersion(verStr))
def __init__(self, versionPredicateStr): """Parse a version predicate string. """ # Fields: # name: package name # pred: list of (comparison string, StrictVersion) versionPredicateStr = versionPredicateStr.strip() if not versionPredicateStr: raise ValueError("empty package restriction") match = re_validPackage.match(versionPredicateStr) if not match: raise ValueError("bad package name in %r" % versionPredicateStr) self.name, paren = match.groups() paren = paren.strip() if paren: match = re_paren.match(paren) if not match: raise ValueError("expected parenthesized list: %r" % paren) str = match.groups()[0] self.pred = [splitUp(aPred) for aPred in str.split(",")] if not self.pred: raise ValueError("empty parenthesized list in %r" % versionPredicateStr) else: self.pred = []
def satisfied_by(self, version): """True if version is compatible with all the predicates in self. The parameter version must be acceptable to the StrictVersion constructor. It may be either a string or StrictVersion. """ for cond, ver in self.pred: if not compmap[cond](version, ver): return False return True
def __init__(self, vstring='0.0.0'): distutils.version.StrictVersion.__init__(self, vstring)
def __cmp__(self, other): if other is None: return False elif isinstance(other, string_types): other = distutils.version.StrictVersion(other) return distutils.version.StrictVersion.__cmp__(self, other) else: return distutils.version.StrictVersion.__cmp__(self, other)
def _pg_version_is_at_least(connection, version): try: v = distutils.version.LooseVersion(version) pg_version = connection.execute('select version();').fetchone() pg_version_number = pg_version[0].split()[1] pv = distutils.version.LooseVersion(pg_version_number) return v <= pv except ValueError: return False
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)
def version_info(self): return {'backend':'TextEncoder','version':1}
def version_info(self): return { 'backend':self.backend, 'version':str(subprocess.check_output([self.backend, '-version'], stderr=subprocess.STDOUT)), 'cmdline':self.cmdline }
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())
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 code runs before importing the rest of gym, since we may # print a warning at load time.) # # It's generally not best practice to configure the logger in a # library. We choose to do so because, empirically, many of our users # are unfamiliar with Python's logging configuration, and never find # their way to enabling our logging. Users who are aware of how to # configure Python's logging do have to accept a bit of incovenience # (generally by caling `gym.undo_logger_setup()`), but in exchange, # the library becomes much more usable for the uninitiated. # # Gym's design goal generally is to be simple and intuitive, and while # the tradeoff is definitely not obvious in this case, we've come down # on the side of auto-configuring the logger.
def archive_dir_name(bundle_path, version): dir_path, bundle_filename = os.path.split(bundle_path) bundle_name, bundle_ext = os.path.splitext(bundle_filename) # GitHub will replace spaces with periods; dashes look better bundle_name = bundle_name.replace(' ', '-') return dir_path, '%s-%s%s' % (bundle_name, version, bundle_ext)
def tag_for_version(version): return 'v' + version