本文整理汇总了Python中packaging.requirements.Requirement方法的典型用法代码示例。如果您正苦于以下问题:Python requirements.Requirement方法的具体用法?Python requirements.Requirement怎么用?Python requirements.Requirement使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类packaging.requirements
的用法示例。
在下文中一共展示了requirements.Requirement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: version_info
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def version_info(parser):
versions = OrderedDict()
to_visit = {"tox"}
while to_visit:
current = to_visit.pop()
current_dist = importlib_metadata.distribution(current)
current_name = canonicalize_name(current_dist.metadata["name"])
versions[current_name] = current_dist.version
if current_dist.requires is not None:
for require in current_dist.requires:
pkg = Requirement(require)
pkg_name = canonicalize_name(pkg.name)
if (
pkg.marker is None or pkg.marker.evaluate({"extra": ""})
) and pkg_name not in versions:
to_visit.add(pkg_name)
set_section(parser, "tox:versions", versions)
示例2: test_format
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def test_format():
root = RootDependency()
text = (
'hypothesis[django]<=3.0.0; '
'python_version == "2.7" and '
'platform_python_implementation == "CPython"'
)
req = PackagingRequirement(text)
deps = DependencyMaker.from_requirement(root, req)
# test dep
assert deps[0].name == 'hypothesis'
assert deps[1].name == 'hypothesis[django]'
assert str(deps[0].constraint) == '<=3.0.0'
assert str(deps[0].marker).startswith('python_version == "2.7"')
# test format
req = Requirement(dep=deps[0], lock=False)
req.extra_deps = (deps[1], )
result = PIPConverter(lock=False)._format_req(req=req)
assert 'hypothesis[django]' in result
assert '<=3.0.0' in result
assert 'python_version == "2.7"' in result
assert 'from root' not in result
assert result.startswith(text)
示例3: strip_extras_markers_from_requirement
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
"""
Strips extras markers from requirement instances.
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement req: A packaging requirement to clean
:return: A cleaned requirement
:rtype: PackagingRequirement
"""
if req is None:
raise TypeError("Must pass in a valid requirement, received {0!r}".format(req))
if getattr(req, "marker", None) is not None:
marker = req.marker # type: TMarker
marker._markers = _strip_extras_markers(marker._markers)
if not marker._markers:
req.marker = None
else:
req.marker = marker
return req
示例4: fix_requires_python_marker
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [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
示例5: get_package_from_requirement
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [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
示例6: dependencies
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def dependencies(self):
# type: () -> Tuple[Dict[S, PackagingRequirement], List[Union[S, PackagingRequirement]], List[S]]
build_deps = [] # type: List[Union[S, PackagingRequirement]]
setup_deps = [] # type: List[S]
deps = {} # type: Dict[S, PackagingRequirement]
if self.setup_info:
setup_info = self.setup_info.as_dict()
deps.update(setup_info.get("requires", {}))
setup_deps.extend(setup_info.get("setup_requires", []))
build_deps.extend(setup_info.get("build_requires", []))
if self.extras and self.setup_info.extras:
for dep in self.extras:
if dep not in self.setup_info.extras:
continue
extras_list = self.setup_info.extras.get(dep, []) # type: ignore
for req_instance in extras_list: # type: ignore
deps[req_instance.key] = req_instance
if self.pyproject_requires:
build_deps.extend(list(self.pyproject_requires))
setup_deps = list(set(setup_deps))
build_deps = list(set(build_deps))
return deps, setup_deps, build_deps
示例7: _reverse_dependencies
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def _reverse_dependencies(self, cache_keys):
"""
Returns a lookup table of reverse dependencies for all the given cache keys.
Example input:
[('pep8', '1.5.7'),
('flake8', '2.4.0'),
('mccabe', '0.3'),
('pyflakes', '0.8.1')]
Example output:
{'pep8': ['flake8'],
'flake8': [],
'mccabe': ['flake8'],
'pyflakes': ['flake8']}
"""
# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),
# ('flake8', 'mccabe'), ...]
return lookup_table((key_from_req(Requirement(dep_name)), name)
for name, version_and_extras in cache_keys
for dep_name in self.cache[name][version_and_extras])
示例8: main
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def main():
"""Resolve requirements as project names on PyPI.
The requirements are taken as command-line arguments
and the resolution result will be printed to stdout.
"""
if len(sys.argv) == 1:
print("Usage:", sys.argv[0], "<PyPI project name(s)>")
return
# Things I want to resolve.
reqs = sys.argv[1:]
requirements = [Requirement(r) for r in reqs]
# Create the (reusable) resolver.
provider = PyPIProvider()
reporter = BaseReporter()
resolver = Resolver(provider, reporter)
# Kick off the resolution process, and get the final result.
print("Resolving", ", ".join(reqs))
result = resolver.resolve(requirements)
display_resolution(result)
示例9: _determine_filtered_package_requirements
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def _determine_filtered_package_requirements(self) -> List[Requirement]:
"""
Parse the configuration file for [blacklist]packages
Returns
-------
list of packaging.requirements.Requirement
For all PEP440 package specifiers
"""
filtered_requirements: Set[Requirement] = set()
try:
lines = self.configuration["blacklist"]["packages"]
package_lines = lines.split("\n")
except KeyError:
package_lines = []
for package_line in package_lines:
package_line = package_line.strip()
if not package_line or package_line.startswith("#"):
continue
filtered_requirements.add(Requirement(package_line))
return list(filtered_requirements)
示例10: run
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def run(specs, requirements_file, *args, **kwargs):
if not specs: # then, assume all in the requirements file
regex = re.compile(r"(^|\n|\n\r).*==")
specs = []
previous_versions = {}
with open(requirements_file) as f:
for line in f:
if regex.search(line) and not line.lstrip().startswith("#"):
req = Requirement(line.split("\\")[0])
# Deliberately strip the specifier (aka. the version)
version = req.specifier
req.specifier = None
specs.append(str(req))
previous_versions[str(req)] = version
kwargs["previous_versions"] = previous_versions
if isinstance(specs, str):
specs = [specs]
return run_packages(specs, requirements_file, *args, **kwargs)
示例11: test_interactive_upgrade_request_repeat_question
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def test_interactive_upgrade_request_repeat_question(capsys):
old = Requirement("hashin==0.9")
old_version = old.specifier
new = Requirement("hashin==0.10")
new_version = new.specifier
questions = []
def mock_input(question):
questions.append(question)
if len(questions) == 1:
return "X" # anything not recognized
elif len(questions) == 2:
return "Y"
raise NotImplementedError(questions)
with mock.patch("hashin.input") as mocked_input:
mocked_input.side_effect = mock_input
result = hashin.interactive_upgrade_request("hashin", old_version, new_version)
assert result == "YES"
示例12: test_interactive_upgrade_request_help
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def test_interactive_upgrade_request_help(capsys):
old = Requirement("hashin==0.9")
old_version = old.specifier
new = Requirement("hashin==0.10")
new_version = new.specifier
questions = []
def mock_input(question):
questions.append(question)
if len(questions) == 1:
return "?"
elif len(questions) == 2:
return "Y"
raise NotImplementedError(questions)
with mock.patch("hashin.input") as mocked_input:
mocked_input.side_effect = mock_input
result = hashin.interactive_upgrade_request("hashin", old_version, new_version)
assert result == "YES"
示例13: _is_same_dep
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def _is_same_dep(cls, dep1, dep2):
"""Definitions are the same if they refer to the same package, even if versions differ."""
dep1_name = canonicalize_name(requirements.Requirement(dep1).name)
try:
dep2_name = canonicalize_name(requirements.Requirement(dep2).name)
except requirements.InvalidRequirement:
# we couldn't parse a version, probably a URL
return False
return dep1_name == dep2_name
示例14: ensure_requires_satisfied
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def ensure_requires_satisfied(config, requires, min_version):
missing_requirements = []
failed_to_parse = False
deps = []
exists = set()
for require in requires + [min_version]:
# noinspection PyBroadException
try:
package = requirements.Requirement(require)
# check if the package even applies
if package.marker and not package.marker.evaluate({"extra": ""}):
continue
package_name = canonicalize_name(package.name)
if package_name not in exists:
deps.append(DepConfig(require, None))
exists.add(package_name)
dist = importlib_metadata.distribution(package.name)
if not package.specifier.contains(dist.version, prereleases=True):
raise MissingDependency(package)
except requirements.InvalidRequirement as exception:
failed_to_parse = True
error("failed to parse {!r}".format(exception))
except Exception as exception:
verbosity1("could not satisfy requires {!r}".format(exception))
missing_requirements.append(str(requirements.Requirement(require)))
if failed_to_parse:
raise tox.exception.BadRequirement()
if WITHIN_PROVISION and missing_requirements:
msg = "break infinite loop provisioning within {} missing {}"
raise tox.exception.Error(msg.format(sys.executable, missing_requirements))
config.run_provision = bool(len(missing_requirements))
return deps
示例15: build
# 需要导入模块: from packaging import requirements [as 别名]
# 或者: from packaging.requirements import Requirement [as 别名]
def build(config, session):
build_info = get_build_info(config.setupdir)
package_venv = session.getvenv(config.isolated_build_env)
package_venv.envconfig.deps_matches_subset = True
# we allow user specified dependencies so the users can write extensions to
# install additional type of dependencies (e.g. binary)
user_specified_deps = package_venv.envconfig.deps
package_venv.envconfig.deps = [DepConfig(r, None) for r in build_info.requires]
package_venv.envconfig.deps.extend(user_specified_deps)
if package_venv.setupenv():
package_venv.finishvenv()
if isinstance(package_venv.status, Exception):
raise package_venv.status
build_requires = get_build_requires(build_info, package_venv, config.setupdir)
# we need to filter out requirements already specified in pyproject.toml or user deps
base_build_deps = {
canonicalize_name(Requirement(r.name).name) for r in package_venv.envconfig.deps
}
build_requires_dep = [
DepConfig(r, None)
for r in build_requires
if canonicalize_name(Requirement(r).name) not in base_build_deps
]
if build_requires_dep:
with package_venv.new_action("build_requires", package_venv.envconfig.envdir) as action:
package_venv.run_install_command(packages=build_requires_dep, action=action)
package_venv.finishvenv()
return perform_isolated_build(build_info, package_venv, config.distdir, config.setupdir)