本文整理汇总了Python中pkg_resources.resource_string方法的典型用法代码示例。如果您正苦于以下问题:Python pkg_resources.resource_string方法的具体用法?Python pkg_resources.resource_string怎么用?Python pkg_resources.resource_string使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pkg_resources
的用法示例。
在下文中一共展示了pkg_resources.resource_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __readStandardObisInfo
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def __readStandardObisInfo(cls, standard, codes):
if standard != Standard.DLMS:
for it in cls.__getObjects(standard):
tmp = GXStandardObisCode(it.logicalName.split('.'))
tmp.interfaces = str(it.objectType)
tmp.description = it.description
tmp.uiDataType = it.uiDataType
codes.append(tmp)
str_ = pkg_resources.resource_string(__name__, "OBISCodes.txt").decode("utf-8")
str_ = str_.replace("\n", "\r")
rows = str_.split('\r')
for it in rows:
if it and not it.startswith("#"):
items = it.split(';')
obis = items[0].split('.')
try:
code_ = GXStandardObisCode(obis, str(items[3]) + "; " + str(items[4]) + "; " + str(items[5]) + "; " + str(items[6]) + "; " + str(items[7]), str(items[1]), str(items[2]))
codes.append(code_)
except UnicodeEncodeError:
pass
示例2: get_win_launcher
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
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)
示例3: load_template_source
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
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).
"""
if resource_string is not None:
pkg_name = 'templates/' + template_name
for app_config in apps.get_app_configs():
try:
resource = resource_string(app_config.name, pkg_name)
except Exception:
continue
if six.PY2:
resource = resource.decode(self.engine.file_charset)
return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
raise TemplateDoesNotExist(template_name)
示例4: get_win_launcher
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
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)
示例5: test_fetch_uses_combined_ca_bundle_otherwise
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
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))
示例6: read_resource
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
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)
示例7: load_migration
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def load_migration(plugin, filename, module_name=None):
'''
Load a migration from its python file
:returns: the loaded module
'''
module_name = module_name or _module_name(plugin)
basename = os.path.splitext(os.path.basename(filename))[0]
name = '.'.join((module_name, 'migrations', basename))
filename = os.path.join('migrations', filename)
try:
script = resource_string(module_name, filename)
except Exception:
msg = 'Unable to load file {} from module {}'.format(filename, module_name)
raise MigrationError(msg)
spec = importlib.util.spec_from_loader(name, loader=None)
module = importlib.util.module_from_spec(spec)
exec(script, module.__dict__)
module.__file__ = resource_filename(module_name, filename)
return module
示例8: validate_graph
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def validate_graph(graph, shacl_path=None, format='nquads'):
"""Validate the current graph with a SHACL schema.
Uses default schema if not supplied.
"""
if shacl_path:
with open(shacl_path, 'r', encoding='utf-8') as f:
shacl = f.read()
else:
shacl = resource_string('renku', 'data/shacl_shape.json')
return validate(
graph,
shacl_graph=shacl,
inference='rdfs',
meta_shacl=True,
debug=False,
data_graph_format=format,
shacl_graph_format='json-ld',
advanced=True
)
示例9: install
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def install(client, force):
"""Install Git hooks."""
warning_messages = []
for hook in HOOKS:
hook_path = Path(get_hook_path(hook, client.repo.git_dir))
if hook_path.exists():
if not force:
warning_messages.append(
'Hook already exists. Skipping {0}'.format(str(hook_path))
)
continue
else:
hook_path.unlink()
# Make sure the hooks directory exists.
hook_path.parent.mkdir(parents=True, exist_ok=True)
Path(hook_path).write_bytes(
pkg_resources.resource_string(
'renku.data', '{hook}.sh'.format(hook=hook)
)
)
hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)
return warning_messages
示例10: __getObjects
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def __getObjects(cls, standard):
codes = list()
if standard == Standard.ITALY:
str_ = pkg_resources.resource_string(__name__, "Italy.txt").decode("utf-8")
elif standard == Standard.INDIA:
str_ = pkg_resources.resource_string(__name__, "India.txt").decode("utf-8")
elif standard == Standard.SAUDI_ARABIA:
str_ = pkg_resources.resource_string(__name__, "SaudiArabia.txt").decode("utf-8")
if not str_:
return None
str_ = str_.replace("\n", "\r")
rows = str_.split('\r')
for it in rows:
if it and not it.startswith("#"):
items = it.split(';')
if len(items) > 1:
ot = int(items[0])
ln = _GXCommon.toLogicalName(_GXCommon.logicalNameToBytes(items[1]))
version = int(items[2])
desc = items[3]
code_ = GXObisCode(ln, ot, 0, desc)
code_.version = version
if len(items) > 4:
code_.uiDataType = items[4]
codes.append(code_)
return codes
示例11: _run_interface
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def _run_interface(self, runtime):
import json
import os.path as op
import pkg_resources
from bids.layout import parse_file_entities
from bids.layout.writing import build_path
deriv_cfg = pkg_resources.resource_string("nibetaseries",
op.join("data", "derivatives.json"))
deriv_patterns = json.loads(deriv_cfg.decode('utf-8'))['fmriprep_path_patterns']
subject_entities = parse_file_entities(self.inputs.source_file)
betaseries_entities = parse_file_entities(self.inputs.in_file)
# hotfix
betaseries_entities['description'] = betaseries_entities['desc']
subject_entities.update(betaseries_entities)
out_file = build_path(subject_entities, deriv_patterns)
if not out_file:
raise ValueError("the provided entities do not make a valid file")
base_directory = runtime.cwd
if isdefined(self.inputs.base_directory):
base_directory = os.path.abspath(self.inputs.base_directory)
out_path = op.join(base_directory, self.out_path_base, out_file)
os.makedirs(op.dirname(out_path), exist_ok=True)
# copy the file to the output directory
copy(self.inputs.in_file, out_path)
self._results['out_file'] = out_path
return runtime
示例12: resource_string
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def resource_string(self, path):
"""Handy helper for getting resources from our kit."""
data = pkg_resources.resource_string(__name__, path)
return data.decode("utf8")
示例13: student_view
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def student_view(self, context=None):
context_html = self.get_context_student()
template = self.render_template('static/html/scormxblock.html', context_html)
frag = Fragment(template)
frag.add_css(self.resource_string("static/css/scormxblock.css"))
frag.add_javascript(self.resource_string("static/js/src/scormxblock.js"))
settings = {
'version_scorm': self.version_scorm
}
frag.initialize_js('ScormXBlock', json_args=settings)
return frag
示例14: studio_view
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def studio_view(self, context=None):
context_html = self.get_context_studio()
template = self.render_template('static/html/studio.html', context_html)
frag = Fragment(template)
frag.add_css(self.resource_string("static/css/scormxblock.css"))
frag.add_javascript(self.resource_string("static/js/src/studio.js"))
frag.initialize_js('ScormStudioXBlock')
return frag
示例15: render_template
# 需要导入模块: import pkg_resources [as 别名]
# 或者: from pkg_resources import resource_string [as 别名]
def render_template(self, template_path, context):
template_str = self.resource_string(template_path)
template = Template(template_str)
return template.render(Context(context))