Python pkg_resources.get_distribution() Examples
The following are 30
code examples of pkg_resources.get_distribution().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pkg_resources
, or try the search function
.
Example #1
Source File: __main__.py From discord.py with MIT License | 6 votes |
def show_version(): entries = [] entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) version_info = discord.version_info entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) if version_info.releaselevel != 'final': pkg = pkg_resources.get_distribution('discord.py') if pkg: entries.append(' - discord.py pkg_resources: v{0}'.format(pkg.version)) entries.append('- aiohttp v{0.__version__}'.format(aiohttp)) entries.append('- websockets v{0.__version__}'.format(websockets)) uname = platform.uname() entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname)) print('\n'.join(entries))
Example #2
Source File: mlperf_helper.py From models with Apache License 2.0 | 6 votes |
def get_mlperf_log(): """Shielded import of mlperf_log module.""" try: import mlperf_compliance def test_mlperf_log_pip_version(): """Check that mlperf_compliance is up to date.""" import pkg_resources version = pkg_resources.get_distribution("mlperf_compliance") version = tuple(int(i) for i in version.version.split(".")) if version < _MIN_VERSION: tf.compat.v1.logging.warning( "mlperf_compliance is version {}, must be >= {}".format( ".".join([str(i) for i in version]), ".".join([str(i) for i in _MIN_VERSION]))) raise ImportError return mlperf_compliance.mlperf_log mlperf_log = test_mlperf_log_pip_version() except ImportError: mlperf_log = None return mlperf_log
Example #3
Source File: __main__.py From godot-gdscript-toolkit with MIT License | 6 votes |
def main(): arguments = docopt( __doc__, version="gdparse {}".format( pkg_resources.get_distribution("gdtoolkit").version ), ) if not isinstance(arguments, dict): print(arguments) sys.exit(0) for file_path in arguments["<file>"]: with open(file_path, "r") as fh: # TODO: handle exception content = fh.read() tree = parser.parse(content) # TODO: handle exception if arguments["--pretty"]: print(tree.pretty()) elif arguments["--verbose"]: print(tree)
Example #4
Source File: session_info.py From reprexpy with MIT License | 6 votes |
def _get_version_info(self, modname, all_dist_info): try: dist_info = pkg_resources.get_distribution(modname) return dist_info.project_name, dist_info.version except pkg_resources.DistributionNotFound: ml = modname.split('.') if len(ml) > 1: modname = '.'.join(ml[:-1]) return self._get_version_info(modname, all_dist_info) else: tmod = modname.split('.')[0] x = [ (i['project_name'], i['version']) for i in all_dist_info if tmod in i['mods'] ] if x: return x[0] else: return _, _
Example #5
Source File: upgrade.py From apio with GNU General Public License v2.0 | 6 votes |
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")
Example #6
Source File: tb_utility.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def install_package(package, version="upgrade"): from sys import executable from subprocess import check_call result = False if version.lower() == "upgrade": result = check_call([executable, "-m", "pip", "install", package, "--upgrade", "--user"]) else: from pkg_resources import get_distribution current_package_version = None try: current_package_version = get_distribution(package) except Exception: pass if current_package_version is None or current_package_version != version: installation_sign = "==" if ">=" not in version else "" result = check_call([executable, "-m", "pip", "install", package + installation_sign + version, "--user"]) return result
Example #7
Source File: __init__.py From jbox with MIT License | 6 votes |
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)
Example #8
Source File: target_csv.py From target-csv with GNU Affero General Public License v3.0 | 6 votes |
def send_usage_stats(): try: version = pkg_resources.get_distribution('target-csv').version conn = http.client.HTTPConnection('collector.singer.io', 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')
Example #9
Source File: __init__.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #10
Source File: main.py From sawtooth-core with Apache License 2.0 | 6 votes |
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
Example #11
Source File: sawset.py From sawtooth-core with Apache License 2.0 | 6 votes |
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
Example #12
Source File: sawnet.py From sawtooth-core with Apache License 2.0 | 6 votes |
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
Example #13
Source File: sawadm.py From sawtooth-core with Apache License 2.0 | 6 votes |
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
Example #14
Source File: __init__.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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)
Example #15
Source File: main.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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)
Example #16
Source File: __init__.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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)
Example #17
Source File: update.py From IDontSpeakSSL with GNU General Public License v3.0 | 5 votes |
def check_idonspeakssl_version(): latest_idontspeakssl_version = (requests.get(IDONTSPEAKSSL_VERSION_URL)).text if pkg_resources.get_distribution("idontspeakssl").version == latest_idontspeakssl_version: print_green("[i] idontspeakssl is up-to-date.") else: print_red("[!] idontspeakssl is not up-to-date.")
Example #18
Source File: oo_filters.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def oo_merge_hostvars(hostvars, variables, inventory_hostname): """ Merge host and play variables. When ansible version is greater than or equal to 2.0.0, merge hostvars[inventory_hostname] with variables (ansible vars) otherwise merge hostvars with hostvars['inventory_hostname']. Ex: hostvars={'master1.example.com': {'openshift_variable': '3'}, 'openshift_other_variable': '7'} variables={'openshift_other_variable': '6'} inventory_hostname='master1.example.com' returns {'openshift_variable': '3', 'openshift_other_variable': '7'} hostvars=<ansible.vars.hostvars.HostVars object> (Mapping) variables={'openshift_other_variable': '6'} inventory_hostname='master1.example.com' returns {'openshift_variable': '3', 'openshift_other_variable': '6'} """ if not isinstance(hostvars, Mapping): raise errors.AnsibleFilterError("|failed expects hostvars is dictionary or object") if not isinstance(variables, dict): raise errors.AnsibleFilterError("|failed expects variables is a dictionary") if not isinstance(inventory_hostname, basestring): raise errors.AnsibleFilterError("|failed expects inventory_hostname is a string") # pylint: disable=no-member ansible_version = pkg_resources.get_distribution("ansible").version merged_hostvars = {} if LooseVersion(ansible_version) >= LooseVersion('2.0.0'): merged_hostvars = FilterModule.oo_merge_dicts(hostvars[inventory_hostname], variables) else: merged_hostvars = FilterModule.oo_merge_dicts(hostvars[inventory_hostname], hostvars) return merged_hostvars
Example #19
Source File: configure.py From loopchain with Apache License 2.0 | 5 votes |
def _set_package_version(self): icon_versions: dict = globals()['ICON_VERSIONS'] for pkg_name in icon_versions.keys() - {'icon_rc'}: try: version = pkg_resources.get_distribution(pkg_name).version icon_versions[pkg_name] = version except pkg_resources.DistributionNotFound as e: logging.warning(f"get '{pkg_name}' version error : {e}") continue command_result = os.popen('icon_rc -version').read() match_result = re.match(r'([a-z_]+)\s([\da-zA-Z-_\.]+)', command_result) # ('icon_rc', 'vX.X.X') if match_result: icon_rc_version = match_result.group(2) icon_versions['icon_rc'] = icon_rc_version
Example #20
Source File: cli.py From CrawlBox with The Unlicense | 5 votes |
def main(): '''tldextract CLI main command.''' import argparse logging.basicConfig() try: __version__ = pkg_resources.get_distribution('tldextract').version # pylint: disable=no-member except pkg_resources.DistributionNotFound as _: __version__ = '(local)' parser = argparse.ArgumentParser( prog='tldextract', description='Parse hostname from a url or fqdn') parser.add_argument('--version', action='version', version='%(prog)s ' + __version__) # pylint: disable=no-member parser.add_argument('input', metavar='fqdn|url', type=unicode, nargs='*', help='fqdn or url') parser.add_argument('-u', '--update', default=False, action='store_true', help='force fetch the latest TLD definitions') parser.add_argument('-c', '--cache_file', help='use an alternate TLD definition file') parser.add_argument('-p', '--private_domains', default=False, action='store_true', help='Include private domains') args = parser.parse_args() tld_extract = TLDExtract(include_psl_private_domains=args.private_domains) if args.cache_file: tld_extract.cache_file = args.cache_file if args.update: tld_extract.update(True) elif len(args.input) is 0: parser.print_usage() exit(1) for i in args.input: print(' '.join(tld_extract(i))) # pylint: disable=superfluous-parens
Example #21
Source File: parser.py From godot-gdscript-toolkit with MIT License | 5 votes |
def _get_parser( self, name: str, add_metadata: bool = False, grammar_filename: str = "gdscript.lark", ) -> Tree: version: str = pkg_resources.get_distribution("gdtoolkit").version tree: Tree = None cache_filepath: str = os.path.join( self._cache_dirpath, version, name ) + ".pickle" grammar_filepath: str = os.path.join(self._directory, grammar_filename) if not os.path.exists(cache_filepath) or not self._use_grammar_cache: tree = Lark.open( grammar_filepath, parser="lalr", start="start", postlex=Indenter(), propagate_positions=add_metadata, maybe_placeholders=False, ) self.save(tree, cache_filepath) else: tree = self.load(cache_filepath) return tree
Example #22
Source File: metrics.py From gax-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def fill(metrics_headers=()): """Add the metrics headers known to GAX. Return an OrderedDict with all of the metrics headers provided to this function, as well as the metrics known to GAX (such as its own version, the GRPC version, etc.). """ # Create an ordered dictionary with the Python version, which # should go first. answer = collections.OrderedDict(( ('gl-python', platform.python_version()), )) # Add anything that already appears in the passed metrics headers, # in order. for key, value in collections.OrderedDict(metrics_headers).items(): answer[key] = value # Add the GAX and GRPC headers to our metrics. # These come after what may have been passed in (generally the GAPIC # library). answer['gax'] = gax.__version__ # pylint: disable=no-member answer['grpc'] = pkg_resources.get_distribution('grpcio').version # pylint: enable=no-member return answer
Example #23
Source File: conftest.py From setuptools_scm with MIT License | 5 votes |
def pytest_report_header(): import pkg_resources res = [] for pkg in VERSION_PKGS: version = pkg_resources.get_distribution(pkg).version path = __import__(pkg).__file__ res.append("{} version {} from {!r}".format(pkg, version, path)) return res
Example #24
Source File: req.py From oss-ftp with MIT License | 5 votes |
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
Example #25
Source File: scenario_runner.py From scenario_runner with MIT License | 5 votes |
def __init__(self, args): """ Setup CARLA client and world Setup ScenarioManager """ self._args = args if args.timeout: self.client_timeout = float(args.timeout) # First of all, we need to create the client that will send the requests # to the simulator. Here we'll assume the simulator is accepting # requests in the localhost at port 2000. self.client = carla.Client(args.host, int(args.port)) self.client.set_timeout(self.client_timeout) dist = pkg_resources.get_distribution("carla") if LooseVersion(dist.version) < LooseVersion('0.9.8'): raise ImportError("CARLA version 0.9.8 or newer required. CARLA version found: {}".format(dist)) # Load agent if requested via command line args # If something goes wrong an exception will be thrown by importlib (ok here) if self._args.agent is not None: module_name = os.path.basename(args.agent).split('.')[0] sys.path.insert(0, os.path.dirname(args.agent)) self.module_agent = importlib.import_module(module_name) # Create the ScenarioManager self.manager = ScenarioManager(self._args.debug, self._args.sync, self._args.timeout) # Create signal handler for SIGINT self._shutdown_requested = False if sys.platform != 'win32': signal.signal(signal.SIGHUP, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGTERM, self._signal_handler) self._start_wall_time = datetime.now()
Example #26
Source File: version.py From foremast with Apache License 2.0 | 5 votes |
def get_version(): """Retrieve package version.""" version = 'Not installed.' try: version = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: pass return version
Example #27
Source File: main.py From auto-alt-text-lambda-api with MIT License | 5 votes |
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
Example #28
Source File: client.py From osim-rl with MIT License | 5 votes |
def env_create(self, token, env_id = "Run"): route = '/v1/envs/' data = {'env_id': env_id, 'token': token, 'version': pkg_resources.get_distribution("osim-rl").version } try: resp = self._post_request(route, data) except ServerError as e: sys.exit(e.message) self.instance_id = resp['instance_id'] self.env_monitor_start("tmp", force=True) return self.env_reset()
Example #29
Source File: client.py From ibis with Apache License 2.0 | 5 votes |
def version(self): """Return the backend library version. Returns ------- string Version of the backend library. """ # pymapd doesn't have __version__ dist = pkg_resources.get_distribution('pymapd') return pkg_resources.parse_version(dist.version)
Example #30
Source File: utils.py From Dallinger with MIT License | 5 votes |
def dallinger_package_path(): """Return the absolute path of the root directory of the installed Dallinger package: >>> utils.dallinger_package_location() '/Users/janedoe/projects/Dallinger3/dallinger' """ dist = get_distribution("dallinger") src_base = os.path.join(dist.location, dist.project_name) return src_base