本文整理汇总了Python中packaging.specifiers.Specifier方法的典型用法代码示例。如果您正苦于以下问题:Python specifiers.Specifier方法的具体用法?Python specifiers.Specifier怎么用?Python specifiers.Specifier使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类packaging.specifiers
的用法示例。
在下文中一共展示了specifiers.Specifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: specs_to_string
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def specs_to_string(specs):
# type: (List[Union[STRING_TYPE, Specifier]]) -> AnyStr
"""Turn a list of specifier tuples into a string
:param List[Union[Specifier, str]] specs: a list of specifiers to format
:return: A string of specifiers
:rtype: str
"""
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs]) # type: ignore
return extras
return ""
示例2: fix_requires_python_marker
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def fix_requires_python_marker(requires_python):
from packaging.requirements import Requirement as PackagingRequirement
marker_str = ""
if any(requires_python.startswith(op) for op in Specifier._operators.keys()):
spec_dict = defaultdict(set)
# We are checking first if we have leading specifier operator
# if not, we can assume we should be doing a == comparison
specifierset = list(SpecifierSet(requires_python))
# for multiple specifiers, the correct way to represent that in
# a specifierset is `Requirement('fakepkg; python_version<"3.0,>=2.6"')`
marker_key = Variable("python_version")
for spec in specifierset:
operator, val = spec._spec
cleaned_val = Value(val).serialize().replace('"', "")
spec_dict[Op(operator).serialize()].add(cleaned_val)
marker_str = " and ".join(
[
"{0}{1}'{2}'".format(marker_key.serialize(), op, ",".join(vals))
for op, vals in spec_dict.items()
]
)
marker_to_add = PackagingRequirement("fakepkg; {0}".format(marker_str)).marker
return marker_to_add
示例3: get_versions
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def get_versions(specset, group_by_operator=True):
# type: (Union[Set[Specifier], SpecifierSet], bool) -> List[Tuple[STRING_TYPE, STRING_TYPE]]
specs = [_get_specs(x) for x in list(tuple(specset))]
initial_sort_key = lambda k: (k[0], k[1])
initial_grouping_key = operator.itemgetter(0)
if not group_by_operator:
initial_grouping_key = operator.itemgetter(1)
initial_sort_key = operator.itemgetter(1)
version_tuples = sorted(
set((op, version) for spec in specs for op, version in spec), key=initial_sort_key
)
version_tuples = [fix_version_tuple(t) for t in version_tuples]
op_groups = [
(grp, list(map(operator.itemgetter(1), keys)))
for grp, keys in itertools.groupby(version_tuples, key=initial_grouping_key)
]
versions = [
(op, packaging.version.parse(".".join(str(v) for v in val)))
for op, vals in op_groups
for val in vals
]
return sorted(versions, key=operator.itemgetter(1))
示例4: _split_specifierset_str
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _split_specifierset_str(specset_str, prefix="=="):
# type: (str, str) -> Set[Specifier]
"""
Take a specifierset string and split it into a list to join for specifier sets
:param str specset_str: A string containing python versions, often comma separated
:param str prefix: A prefix to use when generating the specifier set
:return: A list of :class:`Specifier` instances generated with the provided prefix
:rtype: Set[Specifier]
"""
specifiers = set()
if "," not in specset_str and " " in specset_str:
values = [v.strip() for v in specset_str.split()]
else:
values = [v.strip() for v in specset_str.split(",")]
if prefix == "!=" and any(v in values for v in DEPRECATED_VERSIONS):
values += DEPRECATED_VERSIONS[:]
for value in sorted(values):
specifiers.add(Specifier("{0}{1}".format(prefix, value)))
return specifiers
示例5: _get_specifiers_from_markers
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _get_specifiers_from_markers(marker_item):
"""
Given a marker item, get specifiers from the version marker
:param :class:`~packaging.markers.Marker` marker_sequence: A marker describing a version constraint
:return: A set of specifiers corresponding to the marker constraint
:rtype: Set[Specifier]
"""
specifiers = set()
if isinstance(marker_item, tuple):
variable, op, value = marker_item
if variable.value != "python_version":
return specifiers
if op.value == "in":
specifiers.update(_split_specifierset_str(value.value, prefix="=="))
elif op.value == "not in":
specifiers.update(_split_specifierset_str(value.value, prefix="!="))
else:
specifiers.add(Specifier("{0}{1}".format(op.value, value.value)))
elif isinstance(marker_item, list):
parts = get_specset(marker_item)
if parts:
specifiers.update(parts)
return specifiers
示例6: pyspec_from_markers
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def pyspec_from_markers(marker):
if marker._markers[0][0] != 'python_version':
return
op = marker._markers[0][1].value
version = marker._markers[0][2].value
specset = set()
if op == "in":
specset.update(
Specifier("=={0}".format(v.strip()))
for v in version.split(",")
)
elif op == "not in":
specset.update(
Specifier("!={0}".format(v.strip()))
for v in version.split(",")
)
else:
specset.add(Specifier("".join([op, version])))
if specset:
return specset
return None
示例7: _format_pyspec
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _format_pyspec(specifier):
if isinstance(specifier, str):
if not any(op in specifier for op in Specifier._operators.keys()):
specifier = "=={0}".format(specifier)
specifier = Specifier(specifier)
if specifier.operator == "==" and specifier.version.endswith(".*"):
specifier = Specifier("=={0}".format(specifier.version[:-2]))
try:
op = REPLACE_RANGES[specifier.operator]
except KeyError:
return specifier
version = specifier.version.replace(".*", "")
curr_tuple = _tuplize_version(version)
try:
next_tuple = (curr_tuple[0], curr_tuple[1] + 1)
except IndexError:
next_tuple = (curr_tuple[0], 1)
specifier = Specifier("{0}{1}".format(op, _format_version(next_tuple)))
return specifier
示例8: default
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def default(self, obj): # noqa:E0202 # noqa:W0221
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, PackagingRequirement):
return obj.__dict__
elif isinstance(obj, set):
return tuple(obj)
elif isinstance(obj, (Specifier, SpecifierSet, Marker)):
return str(obj)
else:
return json.JSONEncoder.default(self, obj)
示例9: _format_pyspec
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _format_pyspec(specifier):
# type: (Union[STRING_TYPE, Specifier]) -> Specifier
if isinstance(specifier, str):
if not any(op in specifier for op in Specifier._operators.keys()):
specifier = "=={0}".format(specifier)
specifier = Specifier(specifier)
version = getattr(specifier, "version", specifier).rstrip()
if version and version.endswith("*"):
if version.endswith(".*"):
version = version[:-2]
version = version.rstrip("*")
specifier = Specifier("{0}{1}".format(specifier.operator, version))
try:
op = REPLACE_RANGES[specifier.operator]
except KeyError:
return specifier
curr_tuple = _tuplize_version(version)
try:
next_tuple = (curr_tuple[0], curr_tuple[1] + 1)
except IndexError:
next_tuple = (curr_tuple[0], 1)
if not next_tuple[1] <= MAX_VERSIONS[next_tuple[0]]:
if specifier.operator == "<" and curr_tuple[1] <= MAX_VERSIONS[next_tuple[0]]:
op = "<="
next_tuple = (next_tuple[0], curr_tuple[1])
else:
return specifier
specifier = Specifier("{0}{1}".format(op, _format_version(next_tuple)))
return specifier
示例10: _get_specs
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _get_specs(specset):
if specset is None:
return
if is_instance(specset, Specifier):
new_specset = SpecifierSet()
specs = set()
specs.add(specset)
new_specset._specs = frozenset(specs)
specset = new_specset
if isinstance(specset, str):
specset = SpecifierSet(specset)
result = []
for spec in set(specset):
version = spec.version
op = spec.operator
if op in ("in", "not in"):
versions = version.split(",")
op = "==" if op == "in" else "!="
for ver in versions:
result.append((op, _tuplize_version(ver.strip())))
else:
result.append((spec.operator, _tuplize_version(spec.version)))
return sorted(result, key=operator.itemgetter(1))
# TODO: Rename this to something meaningful
示例11: normalize_specifier_set
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def normalize_specifier_set(specs):
# type: (Union[str, SpecifierSet]) -> Optional[Set[Specifier]]
"""Given a specifier set, a string, or an iterable, normalize the specifiers
.. note:: This function exists largely to deal with ``pyzmq`` which handles
the ``requires_python`` specifier incorrectly, using ``3.7*`` rather than
the correct form of ``3.7.*``. This workaround can likely go away if
we ever introduce enforcement for metadata standards on PyPI.
:param Union[str, SpecifierSet] specs: Supplied specifiers to normalize
:return: A new set of specifiers or specifierset
:rtype: Union[Set[Specifier], :class:`~packaging.specifiers.SpecifierSet`]
"""
if not specs:
return None
if isinstance(specs, set):
return specs
# when we aren't dealing with a string at all, we can normalize this as usual
elif not isinstance(specs, six.string_types):
return {_format_pyspec(spec) for spec in specs}
spec_list = []
for spec in specs.split(","):
spec = spec.strip()
if spec.endswith(".*"):
spec = spec[:-2]
spec = spec.rstrip("*")
spec_list.append(spec)
return normalize_specifier_set(SpecifierSet(",".join(spec_list)))
# TODO: Check if this is used by anything public otherwise make it private
# And rename it to something meaningful
示例12: marker_from_specifier
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def marker_from_specifier(spec):
# type: (STRING_TYPE) -> Marker
if not any(spec.startswith(k) for k in Specifier._operators.keys()):
if spec.strip().lower() in ["any", "<any>", "*"]:
return None
spec = "=={0}".format(spec)
elif spec.startswith("==") and spec.count("=") > 3:
spec = "=={0}".format(spec.lstrip("="))
if not spec:
return None
marker_segments = []
for marker_segment in cleanup_pyspecs(spec):
marker_segments.append(format_pyversion(marker_segment))
marker_str = " and ".join(marker_segments).replace('"', "'")
return Marker(marker_str)
示例13: _get_specs
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _get_specs(specset):
if isinstance(specset, Specifier):
specset = str(specset)
if isinstance(specset, str):
specset = SpecifierSet(specset.replace(".*", ""))
return [
(spec._spec[0], _tuplize_version(spec._spec[1]))
for spec in getattr(specset, "_specs", [])
]
示例14: update_req
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def update_req(req):
"""Updates a given req object with the latest version."""
if not req.name:
return req, None
info = get_package_info(req.name)
if info['info'].get('_pypi_hidden'):
print('{} is hidden on PyPI and will not be updated.'.format(req))
return req, None
if _is_pinned(req) and _is_version_range(req):
print('{} is pinned to a range and will not be updated.'.format(req))
return req, None
newest_version = _get_newest_version(info)
current_spec = next(iter(req.specifier)) if req.specifier else None
current_version = current_spec.version if current_spec else None
new_spec = Specifier(u'=={}'.format(newest_version))
if not current_spec or current_spec._spec != new_spec._spec:
req.specifier = new_spec
update_info = (
req.name,
current_version,
newest_version)
return req, update_info
return req, None
示例15: _handle_range_constraints
# 需要导入模块: from packaging import specifiers [as 别名]
# 或者: from packaging.specifiers import Specifier [as 别名]
def _handle_range_constraints(
lowest_less_than: Specifier, greatest_greater_than: Specifier
) -> bool:
"""
Check whether two specifiers of the following type are compatible.
It is a helper method for the is_satisfiable function and checks:
- "<=<some-version-number>"
- ">=<some-version-number>"
The equality might be optional.
The pseudo-code is the following:
- is the version number of the lower-than constraint smaller than the one of
the greater-than constraint? E.g. we are in cases like "<=1.0" and ">1.1".
- If yes, then the constraints are unsatisfiable.
- Otherwise, they are satisfiable.
- are the version numbers the same? E.g. "<=1.0,>=1.0"
- If yes, if at least one of them is a strict comparison, then return False, otherwise True.
- otherwise, return True.
:param lowest_less_than: the less-than constraint.
:param greatest_greater_than: the greater than constraint.
:return: False if we are sure the two constraints are not satisfiable, True if we don't know.
"""
version_less_than = Version(lowest_less_than.version)
version_greater_than = Version(greatest_greater_than.version)
if version_less_than < version_greater_than:
return False
elif version_greater_than == version_less_than:
# check if one of them has NOT the equality
one_of_them_is_a_strict_comparison = (
greatest_greater_than.operator == ">"
) or (lowest_less_than.operator == "<")
return not one_of_them_is_a_strict_comparison
else:
return True