我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pkg_resources.get_distribution()。
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 install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist)
def list_package_entrypoints(package_name, ep_types=None, skips=None, filters=None): eps = pkg_resources.get_entry_map( pkg_resources.get_distribution(package_name)) if not ep_types: ep_types = eps.keys() if not skips: skips = [] if not filters: filters = [] if len(ep_types) == 1: names = filter_ep_names(eps, ep_types[0], skips=skips, filters=filters) if names: print(','.join(names)) else: for ep_t in ep_types: print("%s=%s" % (ep_t, ','.join(filter_ep_names(eps, ep_t, skips=skips, filters=filters))))
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist)
def send_usage_stats(): try: version = pkg_resources.get_distribution('target-csv').version conn = http.client.HTTPSConnection('collector.stitchdata.com', timeout=10) conn.connect() params = { 'e': 'se', 'aid': 'singer', 'se_ca': 'target-csv', 'se_ac': 'open', 'se_la': version, } conn.request('GET', '/i?' + urllib.parse.urlencode(params)) response = conn.getresponse() conn.close() except: logger.debug('Collection request failed')
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 collect(): '''Send usage info to Stitch.''' try: version = pkg_resources.get_distribution('target-stitch').version conn = http.client.HTTPSConnection('collector.stitchdata.com', timeout=10) conn.connect() params = { 'e': 'se', 'aid': 'singer', 'se_ca': 'target-stitch', 'se_ac': 'open', 'se_la': version, } conn.request('GET', '/i?' + urllib.parse.urlencode(params)) conn.getresponse() conn.close() except: # pylint: disable=bare-except LOGGER.debug('Collection request failed')
def __call__(self, parser, *a): try: pyldap = get_distribution('pyldap') except Exception: # pragma: nocover_py3 pyldap = get_distribution('python-ldap') version = ( "%(package)s %(version)s\n" "%(pyldap)s %(ldapversion)s\n" "Python %(pyversion)s\n" ) % dict( package=__package__, version=__version__, pyversion=sys.version, pyldap=pyldap.project_name, ldapversion=pyldap.version, ) print(version.strip()) parser.exit()
def ensure_extra_versions_supported(extra): # as this is an optional aid, don't fail if on old version of pip try: talisker_pkg = pkg_resources.get_distribution('talisker') extra_deps = ( set(talisker_pkg.requires([extra])) - set(talisker_pkg.requires()) ) for requirement in extra_deps: pkg = pkg_resources.get_distribution(requirement.project_name) if pkg.version not in requirement.specifier: raise TaliskerVersionException( '{} {} is not supported ({})'.format( requirement.project_name, pkg.version, requirement)) except Exception: logging.getLogger(__name__).debug( 'skipping ensure_extra_versions_supported as exception occured') return True # module level caches for global objects, means we can store all globals in # a single place. This is useful when testing, as we can reset globals easily.
def isLatestVersion(): currentVersion = pkg_resources.get_distribution('catalearn').version r = requests.get('https://pypi.python.org/simple/catalearn/') soup = BeautifulSoup(r.text, "html5lib") allVersions = [] for link in soup.find_all('a'): text = link.get_text() result = re.search('catalearn-(.+)-py3-none-any\.whl', text) if result: allVersions.append(result.group(1)) allVersions.sort() latestVersion = allVersions[-1] return currentVersion == latestVersion
def _get_info(name): metadata = _get_metadata(name) version = pkg_resources.get_distribution(name).version if metadata: if metadata['is_release']: released = 'released' else: released = 'pre-release' sha = metadata['git_version'] else: version_parts = version.split('.') if version_parts[-1].startswith('g'): sha = version_parts[-1][1:] released = 'pre-release' else: sha = "" released = "released" for part in version_parts: if not part.isdigit(): released = "pre-release" return dict(name=name, version=version, sha=sha, released=released)
def pkg_info(project_name=None, include_extras=False): if project_name is None: project_name = PROJECT_NAME try: distribution = pkg_resources.get_distribution(project_name) extras = include_extras and distribution.extras or [] dependencies = [ pkg_info(d) for d in distribution.requires(extras)] return { 'name': project_name, 'version': distribution.version, 'path': distribution.location, 'dependencies': dependencies, } except pkg_resources.ResolutionError: return { 'name': project_name, }
def banner(): title = (BCYAN + center_lines("""\ ?????????? ???????? ??????????????????? ??????????????????? ??????????????????? ?????? ??????????? ?????? ???????????\ """, COLS) + END) for num in range(0, 6): os.system("clear || cls") if num % 2 == 1: print(BRED + center_unicode("?? ?? ?? ?? ?? \r", COLS)) else: print("") print(title) sleep(0.3) flush_puts(center_colors("{0}Ironic Redistribution System ({1}IRS{2})" .format(BYELLOW, BRED, BYELLOW), COLS)) flush_puts(center_colors("{0}Made with ?? by: {1}Kepoor Hampond \ ({2}kepoorhampond{3})".format(BBLUE, BYELLOW, BRED, BYELLOW) + END, COLS)) flush_puts(center_colors("{0}Version: {1}".format(BBLUE, BYELLOW) + pkg_resources.get_distribution("irs").version, COLS))
def cli(ctx): """Check the latest Apio version.""" current_version = get_distribution('apio').version latest_version = get_pypi_latest_version() if latest_version is None: ctx.exit(1) if latest_version == current_version: click.secho('You\'re up-to-date!\nApio {} is currently the ' 'newest version available.'.format(latest_version), fg='green') else: click.secho('You\'re not updated\nPlease execute ' '`pip install -U apio` to upgrade.', fg="yellow")
def main(): if '--version' in sys.argv[1:]: # Can't be part of argparse because the 'packages' is mandatory # print out the version of self import pkg_resources print(pkg_resources.get_distribution('hashin').version) return 0 args = parser.parse_args() try: return run( args.packages, args.requirements_file, args.algorithm, args.python_version, verbose=args.verbose, ) except PackageError as exception: print(str(exception), file=sys.stderr) return 1
def run_write_info_to_outstore(job, context, argv): """ Writing to the output is still problematic, especially from within jobs. So we write some options info into the output store first-thing to trigger errors before doing all the compute if possible. To do this, this job needs to be passed to the root of the workflow """ f = tempfile.NamedTemporaryFile(delete=True) now = datetime.datetime.now() if argv: f.write('{}\n\n'.format(' '.join(argv))) f.write('{}\ntoil-vg version {}\nConfiguration:\n'.format(now, pkg_resources.get_distribution('toil-vg').version)) for key, val in context.config.__dict__.items(): f.write('{}: {}\n'.format(key, val)) f.flush() context.get_out_store().write_output_file(f.name, 'toil-vg-{}.txt'.format( argv[1] if argv and len(argv) > 1 else 'info')) f.close()
def close(self): template = template_env.get_template('main.html') template.stream( program_path=os.path.basename(self._program.path), cobol_lines=self._cobol_lines, items=self._items, comment_format=self._lang.comment_format, bottom_fold_button=not not self._lang.close_block, version=get_distribution('cobolsharp').version, # Needed for template logic isinstance=isinstance, Line=Line, StartBlock=StartBlock, EndBlock=EndBlock, ).dump(self._file) self._cobol_lines = None self._items = None