我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pkg_resources.DistributionNotFound()。
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
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 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 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)
def get_version(): """Retrieve package version.""" version = 'Not installed.' try: version = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: pass return version
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.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.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of setuptools (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U setuptools'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay)
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: # DISTRIBUTE TO SETUPTOOLS UPGRADE HACK (1 of 3 parts) # if we've already set distribute as a conflict to setuptools # then this check has already run before. we don't want it to # run again, and return False, since it would block the uninstall # TODO: remove this later if (self.req.project_name == 'setuptools' and self.conflicts_with and self.conflicts_with.project_name == 'distribute'): return True else: 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
def testResolve(self): ad = pkg_resources.Environment([]) ws = WorkingSet([]) # Resolving no requirements -> nothing to install self.assertEqual(list(ws.resolve([],ad)), []) # Request something not in the collection -> DistributionNotFound self.assertRaises( pkg_resources.DistributionNotFound, ws.resolve, parse_requirements("Foo"), ad ) Foo = Distribution.from_filename( "/foo_dir/Foo-1.2.egg", metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0")) ) ad.add(Foo) ad.add(Distribution.from_filename("Foo-0.9.egg")) # Request thing(s) that are available -> list to activate for i in range(3): targets = list(ws.resolve(parse_requirements("Foo"), ad)) self.assertEqual(targets, [Foo]) list(map(ws.add,targets)) self.assertRaises(VersionConflict, ws.resolve, parse_requirements("Foo==0.9"), ad) ws = WorkingSet([]) # reset # Request an extra that causes an unresolved dependency for "Baz" self.assertRaises( pkg_resources.DistributionNotFound, ws.resolve,parse_requirements("Foo[bar]"), ad ) Baz = Distribution.from_filename( "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo")) ) ad.add(Baz) # Activation list now includes resolved dependency self.assertEqual( list(ws.resolve(parse_requirements("Foo[bar]"), ad)), [Foo,Baz] ) # Requests for conflicting versions produce VersionConflict self.assertRaises(VersionConflict, ws.resolve, parse_requirements("Foo==1.2\nFoo!=1.2"), ad)
def version_info(module): """Get version of a standard python module. Args: module (module): python module object to get version info for. Returns: dict: dictionary of version info. """ if hasattr(module, '__version__'): version = module.__version__ elif hasattr(module, 'VERSION'): version = module.VERSION else: pkgname = module.__name__.split('.')[0] try: info = pkg_resources.get_distribution(pkgname) except (pkg_resources.DistributionNotFound, pkg_resources.RequirementParseError): version = None log.warning( 'version information not found for %s -- what package is this from?' % module.__name__) else: version = info.version return {'version': version}
def pkg_is_installed(name): try: return pkg_resources.get_distribution(name) except pkg_resources.DistributionNotFound: return False
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): if not no_fake: _fake_setuptools() raise ImportError except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("distribute>="+version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of distribute (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U distribute'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) finally: if not no_fake: _create_fake_setuptools_pkg_info(to_dir)
def _get_metadata(package_name): try: return json.loads( pkg_resources.get_distribution( package_name).get_metadata('pbr.json')) except pkg_resources.DistributionNotFound: raise Exception('Package {0} not installed'.format(package_name)) except Exception: return None
def __init__(self): self.fork_blocks = {} if not is_pyevm_available(): raise pkg_resources.DistributionNotFound( "The `py-evm` package is not available. The " "`PyEVMBackend` requires py-evm to be installed and importable. " "Please install the `py-evm` library." ) self.reset_to_genesis() # # Private Accounts API #
def get_pyevm_version(): try: base_version = pkg_resources.parse_version( pkg_resources.get_distribution("py-evm").version ).base_version return Version(base_version) except pkg_resources.DistributionNotFound: return None
def get_pyethereum_version(): try: return Version(pkg_resources.get_distribution("ethereum").version) except pkg_resources.DistributionNotFound: return None
def test_pkg_info_for_missing_dist(self, deps_mocker_stopall): # mock mock_get_distribution = deps_mocker_stopall.MagicMock(name="mock_get_distribution") # patch deps_mocker_stopall.patch.object(pkg_resources, 'get_distribution', mock_get_distribution) mock_get_distribution.side_effect = pkg_resources.DistributionNotFound result = deps.pkg_info() assert PROJECT_NAME == result['name'] # ScarlettOS assert 'version' not in result assert 'path' not in result
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. """ version = _resolve_version(version) 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)