本文整理匯總了Python中packaging.version方法的典型用法代碼示例。如果您正苦於以下問題:Python packaging.version方法的具體用法?Python packaging.version怎麽用?Python packaging.version使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類packaging
的用法示例。
在下文中一共展示了packaging.version方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: Pip6UserAgent
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def Pip6UserAgent(user_agent):
# We're only concerned about pip user agents.
if not user_agent.startswith("pip/"):
raise UnableToParse
# This format was brand new in pip 6.0, so we'll need to restrict it
# to only versions of pip newer than that.
version_str = user_agent.split()[0].split("/", 1)[1]
version = packaging.version.parse(version_str)
if version not in SpecifierSet(">=6", prereleases=True):
raise UnableToParse
try:
return json.loads(user_agent.split(maxsplit=1)[1])
except (json.JSONDecodeError, UnicodeDecodeError, IndexError):
raise UnableToParse from None
示例2: Pip1_4UserAgent
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def Pip1_4UserAgent(*, version, impl_name, impl_version, system_name, system_release):
# This format was brand new in pip 1.4, and went away in pip 6.0, so
# we'll need to restrict it to only versions of pip between 1.4 and 6.0.
if version not in SpecifierSet(">=1.4,<6", prereleases=True):
raise UnableToParse
data = {"installer": {"name": "pip", "version": version}}
if impl_name.lower() != "unknown":
data.setdefault("implementation", {})["name"] = impl_name
if impl_version.lower() != "unknown":
data.setdefault("implementation", {})["version"] = impl_version
if system_name.lower() != "unknown":
data.setdefault("system", {})["name"] = system_name
if system_release.lower() != "unknown":
data.setdefault("system", {})["release"] = system_release
if impl_name.lower() == "cpython":
data["python"] = impl_version
return data
示例3: get_package_from_requirement
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def get_package_from_requirement(req):
# type: (PackagingRequirement) -> Tuple[Package, Set[str]]
versions = set()
if is_pinned_requirement(req):
version = get_pinned_version(req)
versions.add(version)
pkg = get_package_version(req.name, version)
else:
pkg = get_package(req.name)
sorted_releases = list(
sorted(pkg.releases, key=operator.attrgetter("parsed_version"), reverse=True)
)
versions = set(req.specifier.filter((r.version for r in sorted_releases)))
version = next(iter(req.specifier.filter((r.version for r in sorted_releases))))
if pkg.version not in versions:
pkg = get_package_version(pkg.name, version)
return pkg, versions
示例4: find_all_matches
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def find_all_matches(finder, ireq, pre=False):
# type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate]
"""Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A list of matching candidates.
:rtype: list[:class:`~pip._internal.index.InstallationCandidate`]
"""
candidates = clean_requires_python(finder.find_all_candidates(ireq.name))
versions = {candidate.version for candidate in candidates}
allowed_versions = _get_filtered_versions(ireq, versions, pre)
if not pre and not allowed_versions:
allowed_versions = _get_filtered_versions(ireq, versions, True)
candidates = {c for c in candidates if c.version in allowed_versions}
return candidates
示例5: as_dict
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def as_dict(self):
# type: () -> Dict[STRING_TYPE, Any]
prop_dict = {
"name": self.name,
"version": self.version if self._version else None,
"base_dir": self.base_dir,
"ireq": self.ireq,
"build_backend": self.build_backend,
"build_requires": self.build_requires,
"requires": self.requires if self._requirements else None,
"setup_requires": self.setup_requires,
"python_requires": self.python_requires,
"extras": self.extras if self._extras_requirements else None,
"extra_kwargs": self.extra_kwargs,
"setup_cfg": self.setup_cfg,
"setup_py": self.setup_py,
"pyproject": self.pyproject,
}
return {k: v for k, v in prop_dict.items() if v}
示例6: __init__
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def __init__(self, filename):
with open(filename) as f:
case_data = json.load(f)
index_name = os.path.normpath(
os.path.join(
filename, "..", "..", "index", case_data["index"] + ".json"
),
)
with open(index_name) as f:
self.index = json.load(f)
self.root_requirements = [
packaging.requirements.Requirement(r)
for r in case_data["requested"]
]
self.pinned_versions = {}
self.expected_resolution = {
k: packaging.version.parse(v["version"])
for k, v in _iter_resolved(case_data["resolved"])
if _eval_marker(v.get("marker"))
}
示例7: compatible_with
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def compatible_with(
cls,
python_version: PythonVersion,
impl: Optional[str],
plats: Optional[List[str]],
) -> WheelMatcher:
required_python = packaging.version.parse(
".".join(str(v) for v in python_version)
)
# TODO: Add ABI customization.
tag_it = itertools.chain(
packaging.tags.compatible_tags(python_version, impl, plats),
packaging.tags.cpython_tags(python_version, None, plats),
)
tags = {t: i for i, t in enumerate(tag_it)}
return cls(required_python, tags)
示例8: collect_best_dist_urls
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def collect_best_dist_urls(self, name: str) -> Dict[str, str]:
all_dists: DistListMapping = collections.defaultdict(list)
for index_url in self.index_urls:
res = requests.get(f"{index_url}/{name}")
res.raise_for_status()
doc = html5lib.parse(res.content, namespaceHTMLElements=False)
for el in doc.findall(".//a"):
url = el.attrib["href"]
filename = urllib.parse.urlsplit(url).path.rsplit("/", 1)[-1]
wheel_name, ext = filename.rsplit(".", 1)
if ext != "whl":
continue
requires_python = el.attrib.get("data-requires-python")
_, version, tag = _parse_wheel_name(wheel_name)
rank = self.matcher.rank(tag, requires_python)
if rank is None:
continue
all_dists[version].append((rank, url))
urls = {version: min(dists)[1] for version, dists in all_dists.items()}
logger.info("%d URLs found for %s", len(urls), name)
return urls
示例9: process_package_entry
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def process_package_entry(
self, name: str, entry: PackageEntry
) -> Optional[Set[str]]:
more = set()
for dep in entry.dependencies:
try:
req = packaging.requirements.Requirement(dep)
except packaging.requirements.InvalidRequirement:
logger.critical(
"Dropping %s==%s; invalid dependency %r",
name,
entry.version,
dep,
)
return None
more.add(packaging.utils.canonicalize_name(req.name))
return more
示例10: find
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def find(self, package_names: Iterable[str]) -> dict:
data = {}
while package_names:
more: Set[str] = set()
logger.info("Discovering %s", ", ".join(package_names))
for name in package_names:
entries: Dict[str, dict] = {}
for e in self.iter_package_entries(name):
result = self.process_package_entry(name, e)
if result is None:
continue
more |= result
entries[e.version] = {"dependencies": e.dependencies}
data[name] = entries
package_names = {n for n in more if n not in data}
return data
示例11: __init__
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def __init__(self, filename):
case_data = _safe_json_load(filename)
index_name = os.path.join(
INPUTS_DIR, "index", case_data.get("index", "awesome") + ".json",
)
self.index = _safe_json_load(index_name)
self.root_requirements = [
Requirement(_clean_identifier(key), _parse_specifier_set(spec))
for key, spec in case_data["requested"].items()
]
self.pinned_versions = {
entry["name"]: packaging.version.parse(entry["version"])
for entry in case_data["base"]
}
self.expected_resolution = dict(_iter_resolved(case_data["resolved"]))
self.expected_conflicts = set(case_data["conflicts"])
示例12: validate_version
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def validate_version(versionstr, release_type='python-service', pre_ok=True):
"""Given a version string, yield error messages if it is "bad"
Apply our SemVer rules to version strings and report all issues.
"""
if not pre_ok and looks_like_preversion(versionstr):
yield('Version %s looks like a pre-release and the release '
'model does not allow for it' % versionstr)
if release_type not in _VALIDATORS:
yield 'Release Type %r not valid using \'python-service\' instead' % release_type
release_type = 'python-service'
constructor, exception, canonicalise = _VALIDATORS[release_type]
try:
semver = constructor(versionstr)
except exception as err:
yield 'Invalid version: %s' % err
else:
# Make sure we didn't change the version to meet the canonical form.
canonical = canonicalise(semver)
if canonical != versionstr:
yield 'Version %r does not match canonical form %r' % \
(versionstr, canonical)
示例13: get_latest_version_of_package
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def get_latest_version_of_package(package_spec):
if not os.path.isabs(str(package_spec)):
return package_spec
p = py.path.local(package_spec)
if p.check():
return p
if not p.dirpath().check(dir=1):
raise tox.exception.MissingDirectory(p.dirpath())
reporter.info("determining {}".format(p))
candidates = p.dirpath().listdir(p.basename)
if len(candidates) == 0:
raise MissingDependency(package_spec)
if len(candidates) > 1:
version_package = []
for filename in candidates:
version = get_version_from_filename(filename.basename)
if version is not None:
version_package.append((version, filename))
else:
reporter.warning("could not determine version of: {}".format(str(filename)))
if not version_package:
raise tox.exception.MissingDependency(package_spec)
version_package.sort()
_, package_with_largest_version = version_package[-1]
return package_with_largest_version
else:
return candidates[0]
示例14: get_version_from_filename
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def get_version_from_filename(basename):
m = _REGEX_FILE_NAME_WITH_VERSION.match(basename)
if m is None:
return None
version = m.group(1)
try:
return packaging.version.Version(version)
except packaging.version.InvalidVersion:
return None
示例15: DistributeUserAgent
# 需要導入模塊: import packaging [as 別名]
# 或者: from packaging import version [as 別名]
def DistributeUserAgent(*, python, version):
return {"installer": {"name": "distribute", "version": version}, "python": python}