我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pkg_resources.resource_string()。
def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if platform.machine().lower() == 'arm': launcher_fn = launcher_fn.replace(".", "-arm.") if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn)
def load_template_source(self, template_name, template_dirs=None): """ Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name). """ warnings.warn( 'The load_template_sources() method is deprecated. Use ' 'get_template() or get_contents() instead.', RemovedInDjango20Warning, ) for origin in self.get_template_sources(template_name): try: return self.get_contents(origin), origin.name except TemplateDoesNotExist: pass raise TemplateDoesNotExist(template_name)
def __init__(self, path=None): self.path = path or os.getenv('WEBHDFS_CONFIG', self.default_path) if osp.exists(self.path): try: self.config = json.loads(open(self.path).read()) self.schema = json.loads(resource_string(__name__, 'resources/config_schema.json')) #self.schema = open("resources/schema.config").read() try: js.validate(self.config, self.schema) except js.ValidationError as e: print e.message except js.SchemaError as e: print e except ParsingError: raise HdfsError('Invalid configuration file %r.', self.path) _logger.info('Instantiated configuration from %r.', self.path) else: raise HdfsError('Invalid configuration file %r.', self.path)
def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if platform.machine().lower()=='arm': launcher_fn = launcher_fn.replace(".", "-arm.") if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn)
def test_fetch_uses_combined_ca_bundle_otherwise(self): with tempfile.NamedTemporaryFile() as tmp_input, \ tempfile.NamedTemporaryFile(delete=False) as tmp_output: ca_content = pkg_resources.resource_string('leap.common.testing', 'cacert.pem') ca_cert_path = tmp_input.name self._dump_to_file(ca_cert_path, ca_content) pth = 'leap.bitmask.keymanager.tempfile.NamedTemporaryFile' with mock.patch(pth) as mocked: mocked.return_value = tmp_output km = self._key_manager(ca_cert_path=ca_cert_path) get_mock = self._mock_get_response(km, PUBLIC_KEY_OTHER) yield km.fetch_key(ADDRESS_OTHER, REMOTE_KEY_URL) # assert that combined bundle file is passed to get call get_mock.assert_called_once_with(REMOTE_KEY_URL, 'GET') # assert that files got appended expected = self._slurp_file(ca_bundle.where()) + ca_content self.assertEqual(expected, self._slurp_file(tmp_output.name))
def main(): parser = argparse.ArgumentParser(description = "Manages and deploys Onyx clusters.") data = json.loads(resource_string(__name__, 'args.json')) shared_parsers = build_shared_parsers(data['shared-parsers']) attach_subparsers(parser, shared_parsers, data, 0) args = parser.parse_args() arg_vars = vars(args) commands = ['command-0', 'command-1', 'command-2', 'command-3'] command_seq = [ arg_vars.get(k) for k in commands if arg_vars.get(k) is not None ] [success, rets] = engraver_root_dir(getcwd()) if (arg_vars.get('command-0') in ['init', 'configure']) or success: project_root = rets apply(fns.get(tuple(command_seq)), [arg_vars, project_root]) else: print rets
def create_config(cls, workdir): config_path = os.path.join(workdir, CONFIG_FILE_NAME) if not os.path.isfile(config_path): config_template = pkg_resources.resource_string( __package__, 'config_template.yaml') default_values = { 'log_path': os.path.join(workdir, 'cli.log'), 'enable_colors': True } template = Template(config_template) rendered = template.render(**default_values) with open(config_path, 'w') as f: f.write(rendered) f.write(os.linesep) return cls(config_path)
def read_resource(package, fname): """Read the given resource file and return content as string. Parameters ---------- package : string the package name. fname : string the resource file name. Returns ------- content : unicode the content as a unicode string. """ raw_content = pkg_resources.resource_string(package, fname) return raw_content.decode(encoding=bag_encoding, errors=bag_codec_error)
def test_egg_unzipped(pyi_builder): pathex = os.path.join(_MODULES_DIR, 'pyi_egg_unzipped.egg') pyi_builder.test_source( """ # This code is part of the package for testing eggs in `PyInstaller`. import os import pkg_resources # Test ability to load resource. expected_data = 'This is data file for `unzipped`.'.encode('ascii') t = pkg_resources.resource_string('unzipped_egg', 'data/datafile.txt') print('Resource: %s' % t) t_filename = pkg_resources.resource_filename('unzipped_egg', 'data/datafile.txt') print('Resource filename: %s' % t_filename) assert t.rstrip() == expected_data # Test ability that module from .egg is able to load resource. import unzipped_egg assert unzipped_egg.data == expected_data print('Okay.') """, pyi_args=['--paths', pathex], )
def getVersion(): import pkg_resources versionBytes = pkg_resources.resource_string(__name__, "VERSION") version = versionBytes.decode("utf8").strip() return version
def setup_test_files(): test_resources = { 'simple': {'package': 'prov2bigchaindb', 'file': '/assets/graph-example.json'}, 'simple2': {'package': 'prov2bigchaindb', 'file': '/assets/test-example.json'}, 'quantified': {'package': 'prov2bigchaindb', 'file': '/assets/quantified-self.json'}, 'thesis': {'package': 'prov2bigchaindb', 'file': '/assets/thesis-example-full.json'} } return dict( (key, pkg_resources.resource_string(val['package'], val['file'])) for key, val in test_resources.items() )
def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) def get_template(filename): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. These templates use triple-quotes to escape variable substitutions so the scripts get the 2to3 treatment when build on Python 3. The templates cannot use triple-quotes naturally. """ raw_bytes = resource_string('setuptools', template_name) template_str = raw_bytes.decode('utf-8') clean_template = template_str.replace('"""', '') return clean_template if is_script: template_name = 'script template.py' if dev_path: template_name = template_name.replace('.py', ' (dev).py') script_text = (get_script_header(script_text) + get_template(template_name) % locals()) self.write_script(script_name, _to_ascii(script_text), 'b')
def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy,'rb') current = f.read() # we want str, not bytes if sys.version_info >= (3,): current = current.decode() f.close() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) f = open(sitepy,'wb') f.write(source) f.close() self.byte_compile([sitepy]) self.sitepy_installed = True
def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if sys.version_info[0] < 3: return manifest % vars() else: return manifest.decode('utf-8') % vars()
def _load_template(dev_path): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. """ # See https://github.com/pypa/setuptools/issues/134 for info # on script file naming and downstream issues with SVR4 name = 'script.tmpl' if dev_path: name = name.replace('.tmpl', ' (dev).tmpl') raw_bytes = resource_string('setuptools', name) return raw_bytes.decode('utf-8')
def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") source = source.decode('utf-8') current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) with io.open(sitepy) as strm: current = strm.read() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) with io.open(sitepy, 'w', encoding='utf-8') as strm: strm.write(source) self.byte_compile([sitepy]) self.sitepy_installed = True
def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn)
def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if six.PY2: return manifest % vars() else: return manifest.decode('utf-8') % vars()
def _load_template(dev_path): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. """ # See https://bitbucket.org/pypa/setuptools/issue/134 for info # on script file naming and downstream issues with SVR4 name = 'script.tmpl' if dev_path: name = name.replace('.tmpl', ' (dev).tmpl') raw_bytes = resource_string('setuptools', name) return raw_bytes.decode('utf-8')
def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy, 'rb') current = f.read() # we want str, not bytes if PY3: current = current.decode() f.close() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) f = open(sitepy, 'wb') f.write(source) f.close() self.byte_compile([sitepy]) self.sitepy_installed = True
def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if PY2: return manifest % vars() else: return manifest.decode('utf-8') % vars()
def __init__(self, engine): if resource_string is None: raise RuntimeError("Setuptools must be installed to use the egg loader") super(Loader, self).__init__(engine)
def get_contents(self, origin): try: source = resource_string(origin.app_name, origin.pkg_name) except: raise TemplateDoesNotExist(origin) if six.PY2: source = source.decode(self.engine.file_charset) return source
def _cdef(header): ffi.cdef(_pkg_resources.resource_string(__name__, header))
def _cdef(header): ffi.cdef(_pkg_resources.resource_string(__name__, header).decode())
def do_command_generate(self, args): target_location = str(os.path.join(os.getcwd(), 'config.json')) if os.path.isfile(target_location): self.logger.error('config file already exist in current directory.') exit(1) content = pkg_resources.resource_string(__name__, 'template_config.json').decode('utf-8') file = open(target_location, 'w') file.write(content) file.close() self.logger.info('empty config file generated at {}'.format(target_location))
def __resource_string(self, path): # noinspection PyTypeChecker return self.__load_resource(pkg_resources.resource_string, self.__configurer, path) \ .decode("utf-8")
def __get_linesof_script(self, script): format = script['format'] # type: ScriptFormat shellscript = script['script'] # type: str if format is ScriptFormat.PUPPET: tpl = self.__load_resource(pkg_resources.resource_string, self, 'puppet-apply.sh') \ .decode("utf-8") f = NamedTemporaryFile(delete=False) tmpfilename = f.name f.close() os.unlink(f.name) tpl = AtTemplate(tpl) shellscript = tpl.substitute(dict(tmpfilename=tmpfilename, pp=shellscript)) return shellscript.split("\n")
def user_data(config): if type(config['user_data']) == dict: with open(config['user_data']['file']) as f: return f.read() if not config['user_data'] and config['connection'] == 'winrm': ud = pr.resource_string('bossimage', 'win-userdata.txt') else: ud = config['user_data'] return ud
def get_csv(file_name): contents = resource_string('pogoiv', 'data/%s' % file_name) if sys.version_info >= (3, 0): f = StringIO(contents.decode('utf-8')) else: f = BytesIO(contents) return csv.reader(f, delimiter='\t')