def check_if_exists(self):
"""Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately."""
if self.req is None:
return False
try:
self.satisfied_by = pkg_resources.get_distribution(self.req)
except pkg_resources.DistributionNotFound:
return False
except pkg_resources.VersionConflict:
existing_dist = pkg_resources.get_distribution(self.req.project_name)
if self.use_user_site:
if dist_in_usersite(existing_dist):
self.conflicts_with = existing_dist
elif running_under_virtualenv() and dist_in_site_packages(existing_dist):
raise InstallationError("Will not install to the user site because it will lack sys.path precedence to %s in %s"
%(existing_dist.project_name, existing_dist.location))
else:
self.conflicts_with = existing_dist
return True
python类DistributionNotFound()的实例源码
def get_user_agent_default(pkg_name='cloudaux'):
"""
Get default User Agent String.
Try to import pkg_name to get an accurate version number.
return: string
"""
version = '0.0.1'
try:
import pkg_resources
version = pkg_resources.get_distribution(pkg_name).version
except pkg_resources.DistributionNotFound:
pass
except ImportError:
pass
return 'cloudaux/%s' % (version)
def _get_version_from_pkg_resources(self):
"""Obtain a version from pkg_resources or setup-time logic if missing.
This will try to get the version of the package from the pkg_resources
record associated with the package, and if there is no such record
falls back to the logic sdist would use.
"""
try:
requirement = pkg_resources.Requirement.parse(self.package)
provider = pkg_resources.get_provider(requirement)
result_string = provider.version
except pkg_resources.DistributionNotFound:
# The most likely cause for this is running tests in a tree
# produced from a tarball where the package itself has not been
# installed into anything. Revert to setup-time logic.
from pbr import packaging
result_string = packaging.get_version(self.package)
return SemanticVersion.from_pip_string(result_string)
def __init__(self):
if not is_pyethereum21_available():
version = get_pyethereum_version()
if version is None:
raise pkg_resources.DistributionNotFound(
"The `ethereum` package is not available. The "
"`PyEthereum21Backend` requires a 2.0.0+ version of the "
"ethereum package to be installed."
)
elif version not in Spec('>=2.0.0,<2.2.0'):
raise pkg_resources.DistributionNotFound(
"The `PyEthereum21Backend` requires a 2.0.0+ version of the "
"`ethereum` package. Found {0}".format(version)
)
self.reset_to_genesis()
#
# Fork block numbers
#
def __init__(self):
if not is_pyethereum16_available():
version = get_pyethereum_version()
if version is None:
raise pkg_resources.DistributionNotFound(
"The `ethereum` package is not available. The "
"`PyEthereum16Backend` requires a 1.6.x version of the "
"ethereum package to be installed."
)
elif version not in Spec('>=1.6.0,<1.7.0'):
raise pkg_resources.DistributionNotFound(
"The `PyEthereum16Backend` requires a 1.6.x version of the "
"`ethereum` package. Found {0}".format(version)
)
self.reset_to_genesis()
#
# Fork Rules
#
def _get_version_from_pkg_resources(self):
"""Obtain a version from pkg_resources or setup-time logic if missing.
This will try to get the version of the package from the pkg_resources
record associated with the package, and if there is no such record
falls back to the logic sdist would use.
"""
# Lazy import because pkg_resources is costly to import so defer until
# we absolutely need it.
import pkg_resources
try:
requirement = pkg_resources.Requirement.parse(self.package)
provider = pkg_resources.get_provider(requirement)
result_string = provider.version
except pkg_resources.DistributionNotFound:
# The most likely cause for this is running tests in a tree
# produced from a tarball where the package itself has not been
# installed into anything. Revert to setup-time logic.
from pbr import packaging
result_string = packaging.get_version(self.package)
return SemanticVersion.from_pip_string(result_string)
def tests_flatten_egginfo_json_missing_deps(self):
"""
Missing dependencies should not cause a hard failure.
"""
make_dummy_dist(self, (
('requires.txt', '\n'.join([
'uilib>=1.0',
])),
), 'app', '2.0')
working_set = pkg_resources.WorkingSet([self._calmjs_testing_tmpdir])
# Python dependency acquisition failures should fail hard.
with self.assertRaises(pkg_resources.DistributionNotFound):
calmjs_dist.flatten_egginfo_json(['app'], working_set=working_set)
def test_get_version_setup(self):
def mock1(*args, **kwargs):
raise OSError
try:
backup1 = subprocess.check_output
except AttributeError:
backup1 = None
subprocess.check_output = mock1
def mock2(*args, **kwargs):
raise pkg_resources.DistributionNotFound
backup2 = pkg_resources.require
pkg_resources.require = mock2
try:
self.assertEquals("0.0.0-unversioned", _get_version_setup())
finally:
if backup1:
subprocess.check_output = backup1
pkg_resources.require = backup2
def get_version():
"""
Utility to find the version of this application whatever the execution mode (cx_Freeze or normal)
:return:
"""
if getattr(sys, "frozen", False):
# this is cx_Freeze execution mode >> access our generated file
datadir = os.path.dirname(sys.executable)
path = os.path.join(datadir, version_file_cx_freeze)
with open(path, 'rt') as f:
return f.read()
else:
import pkg_resources # part of setuptools
from pkg_resources import DistributionNotFound
try:
return pkg_resources.require("envswitch")[0].version
except DistributionNotFound as e:
# this may happen if the module has not been even locally installed with "pip install ."
from setuptools_scm import get_version
return get_version()
def _get_version_from_pkg_resources(self):
"""Obtain a version from pkg_resources or setup-time logic if missing.
This will try to get the version of the package from the pkg_resources
record associated with the package, and if there is no such record
falls back to the logic sdist would use.
"""
try:
requirement = pkg_resources.Requirement.parse(self.package)
provider = pkg_resources.get_provider(requirement)
return provider.version
except pkg_resources.DistributionNotFound:
# The most likely cause for this is running tests in a tree
# produced from a tarball where the package itself has not been
# installed into anything. Revert to setup-time logic.
from pbr import packaging
return packaging.get_version(self.package)
def command_version(args):
# See http://stackoverflow.com/questions/17583443
from pkg_resources import get_distribution, DistributionNotFound
import os.path
try:
_dist = get_distribution('courseraoauth2client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'courseraoauth2client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
__version__ = 'Please install this project with setup.py'
else:
__version__ = _dist.version
if args.quiet and args.quiet > 0:
print __version__
else:
print "Your %(prog)s's version is:\n\t%(version)s" % {
"prog": sys.argv[0],
"version": __version__
}
def _verify_package(name, operation, version):
try:
module = pkg_resources.get_distribution(name)
except pkg_resources.DistributionNotFound:
raise MissingPackageError(name)
if not operation:
return
required_version = LooseVersion(version)
installed_version = LooseVersion(module.version)
if operation == '==':
check = required_version == installed_version
elif operation == '>':
check = installed_version > required_version
elif operation == '>=':
check = installed_version > required_version or \
installed_version == required_version
else:
raise NotImplementedError(
'operation \'%s\' is not supported' % operation)
if not check:
raise IncorrectPackageVersionError(name, installed_version, operation,
required_version)
def configure_notebook(self):
"""Setup pyramid_notebook integration."""
# Check if we have IPython installed
try:
pkg_resources.get_distribution('IPython[notebook]')
except pkg_resources.DistributionNotFound:
return
try:
import websauna.system.notebook.views
import websauna.system.notebook.adminviews
import websauna.system.notebook.subscribers
except ImportError:
# Have installed IPython[Notebook], but not pyramid_notebook
return
self.config.add_route('admin_shell', '/notebook/admin-shell')
self.config.add_route('shutdown_notebook', '/notebook/shutdown')
self.config.add_route('notebook_proxy', '/notebook/*remainder')
self.config.scan(websauna.system.notebook.views)
self.config.scan(websauna.system.notebook.adminviews)
self.config.scan(websauna.system.notebook.subscribers)
self.config.registry.features.add("notebook")
def test_entry_point_class_list(config_with_files):
"""EntryPointClassList is a special ConfigSetting which reads its value from a pkg_resources
entry point which contains a list of classes published by any (possibly other) egg."""
fixture = config_with_files
# Because we cannot remove EasterEggs from pkg_resources, the next test must happen after
# this one. The next check just ensures that we know when that does not happen:
with expected(pkg_resources.DistributionNotFound):
pkg_resources.require('test-inject')
fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithEntryPointClassList')
# Publish some classes on the entry point being tested
line = 'ListedClass1 = reahl.component_dev.test_config:ListedClass1'
easter_egg.add_entry_point_from_line('some.test.entrypoint', line)
line = 'ListedClass2 = reahl.component_dev.test_config:ListedClass2'
easter_egg.add_entry_point_from_line('some.test.entrypoint', line)
# Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)
config = StoredConfiguration(fixture.config_dir.name)
config.configure()
# The classes are found from the entry point
assert set(config.some_key.some_setting) == {ListedClass1, ListedClass2}
def get_edi_version():
"""
Get the version of the current edi installation or the version derived from git.
:return: full edi version string
"""
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
git_dir = os.path.join(project_root, ".git")
if os.path.isdir(git_dir):
# do import locally so that we do not depend on setuptools_scm for the released version
from setuptools_scm import get_version
return get_version(root=project_root)
else:
try:
return pkg_resources.get_distribution('edi').version
except pkg_resources.DistributionNotFound:
return edi_fallback_version
def show_entry_map(self):
"""
Show entry map for a package
@param dist: package
@param type: srting
@returns: 0 for success or 1 if error
"""
pprinter = pprint.PrettyPrinter()
try:
entry_map = pkg_resources.get_entry_map(self.options.show_entry_map)
if entry_map:
pprinter.pprint(entry_map)
except pkg_resources.DistributionNotFound:
self.logger.error("Distribution not found: %s" \
% self.options.show_entry_map)
return 1
return 0
def show_entry_map(self):
"""
Show entry map for a package
@param dist: package
@param type: srting
@returns: 0 for success or 1 if error
"""
pprinter = pprint.PrettyPrinter()
try:
entry_map = pkg_resources.get_entry_map(self.options.show_entry_map)
if entry_map:
pprinter.pprint(entry_map)
except pkg_resources.DistributionNotFound:
self.logger.error("Distribution not found: %s" \
% self.options.show_entry_map)
return 1
return 0
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def create_parent_parser(prog_name):
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help=False)
parent_parser.add_argument(
'-v', '--verbose',
action='count',
help='enable more verbose output')
try:
version = pkg_resources.get_distribution(DISTRIBUTION_NAME).version
except pkg_resources.DistributionNotFound:
version = 'UNKNOWN'
parent_parser.add_argument(
'-V', '--version',
action='version',
version=(DISTRIBUTION_NAME + ' (Hyperledger Sawtooth) version {}')
.format(version),
help='display version information')
return parent_parser
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def get_version(pkg):
try:
version = pkg_resources.get_distribution(pkg).version
return version
except pkg_resources.DistributionNotFound:
logger.error('`{}` is not installed'.format(pkg))
def assert_package_not_installed(name):
try:
pkg_resources.get_distribution(name)
except pkg_resources.DistributionNotFound:
return
else:
raise RuntimeError(
"Found %r. This has been superseded by 'sentry-plugins', so please uninstall." % name
)
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspath(to_dir)
# prior to importing, capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
except ImportError:
# pkg_resources not available; setuptools is not installed; download
pass
except pkg_resources.DistributionNotFound:
# no version of setuptools was found; allow download
pass
except pkg_resources.VersionConflict as VC_err:
if imported:
_conflict_bail(VC_err, version)
# otherwise, unload pkg_resources to allow the downloaded version to
# take precedence.
del pkg_resources
_unload_pkg_resources()
return _do_download(version, download_base, to_dir, download_delay)