本文整理匯總了Python中pkg_resources.resource_listdir方法的典型用法代碼示例。如果您正苦於以下問題:Python pkg_resources.resource_listdir方法的具體用法?Python pkg_resources.resource_listdir怎麽用?Python pkg_resources.resource_listdir使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pkg_resources
的用法示例。
在下文中一共展示了pkg_resources.resource_listdir方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def __init__(self, package_paths=None):
# Array of gpkg names to SingleMPackage objects
self._hmms_and_positions = {}
if package_paths:
self.singlem_packages = [SingleMPackage.acquire(path) for path in package_paths]
logging.info("Loaded %i SingleM packages" % len(self.singlem_packages))
else:
# Prefer production DB directory
pkg_resources_db_directory = 'data'
pkg_paths = pkg_resources.resource_listdir('singlem',pkg_resources_db_directory)
basedir = pkg_resources.resource_filename('singlem',pkg_resources_db_directory)
logging.debug("Searching for SingleM packages via pkg_resources in %s .." % basedir)
pkg_paths = [os.path.join(basedir,d) for d in pkg_paths if d[-5:]=='.spkg']
if len(pkg_paths) == 0:
raise Exception("Unable to find any SingleM packages using pkg_resources")
logging.debug("Found %i SingleM packages: %s" % (len(pkg_paths),
', '.join(pkg_paths)))
self.singlem_packages = [SingleMPackage.acquire(path) for path in pkg_paths]
for pkg in self.singlem_packages:
self._hmms_and_positions[pkg.base_directory()] = pkg
示例2: scan_subpackages
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def scan_subpackages(cls, package: str) -> Sequence[str]:
"""Return a list of sub-packages defined under a named package."""
# FIXME use importlib.resources in python 3.7
if "." in package:
package, sub_pkg = package.split(".", 1)
else:
sub_pkg = "."
if not pkg_resources.resource_isdir(package, sub_pkg):
raise ModuleLoadError(f"Undefined package {package}")
found = []
joiner = "" if sub_pkg == "." else f"{sub_pkg}."
for sub_path in pkg_resources.resource_listdir(package, sub_pkg):
if pkg_resources.resource_exists(
package, f"{sub_pkg}/{sub_path}/__init__.py"
):
found.append(f"{package}.{joiner}{sub_path}")
return found
示例3: manpages_helper
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def manpages_helper(self):
"""Verify or install COT's manual pages.
Returns:
tuple: (result, message)
"""
try:
resource_listdir("COT", "docs/man")
except OSError as exc:
return False, "UNABLE TO FIND PAGES: " + str(exc)
man_dir = guess_manpath()
if self.verify_only:
return verify_manpages(man_dir)
else:
return install_manpages(man_dir)
示例4: get_migrations
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def get_migrations():
"""Return a sorted list of versions and migration modules."""
migrations = []
for file_ in pkg_resources.resource_listdir(
'renku.core.management', 'migrations'
):
match = re.search(r'm_([0-9]{4})__[a-zA-Z0-9_-]*.py', file_)
if match is None: # migration files match m_0000__[name].py format
continue
version = int(match.groups()[0])
path = 'renku.core.management.migrations.{}'.format(Path(file_).stem)
migrations.append((version, path))
migrations = sorted(migrations, key=lambda v: v[1].lower())
return migrations
示例5: fetch_schema_cityobjects
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def fetch_schema_cityobjects(self, folder_schemas=None):
if folder_schemas is None:
#-- fetch proper schema from the stored ones
tmp = resource_listdir(__name__, '/schemas/')
tmp.sort()
v = tmp[-1]
try:
schema = resource_filename(__name__, '/schemas/%s/cityjson.schema.json' % (v))
except:
return (False, None)
else:
schema = os.path.join(folder_schemas, 'cityjson.schema.json')
abs_path = os.path.abspath(os.path.dirname(schema))
sco_path = abs_path + '/cityobjects.schema.json'
#-- because Windows uses \ and not /
if platform == "darwin" or platform == "linux" or platform == "linux2":
base_uri = 'file://{}/'.format(abs_path)
else:
base_uri = 'file:///{}/'.format(abs_path.replace('\\', '/'))
jsco = jsonref.loads(open(sco_path).read(), jsonschema=True, base_uri=base_uri)
# jsco = json.loads(open(sco_path).read())
return (True, jsco)
示例6: get
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def get(name):
if not has(name):
data = None
dirname = name + "_registry"
for fname in sorted(resource_listdir(__name__, dirname)):
if os.path.splitext(fname)[1] != ".json":
continue
fname = resource_filename(__name__, os.path.join(dirname, fname))
with open(fname, "r") as fp:
chunk = json.load(fp)
if data is None:
data = chunk
elif isinstance(data, list):
data.extend(chunk)
elif isinstance(data, dict):
data.updated(chunk)
if data is None:
raise ValueError("Failed to load registry {}".format(name))
save(name, data)
return _registry[name]
示例7: _unpack_assets
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def _unpack_assets(output_dir, module, asset_root, execute, current_path):
"""
The internal helper function for unpack_assets(...) recursion.
:param current_path: Records the current
"""
for asset in pkg_resources.resource_listdir(module, current_path):
asset_target = os.path.join(os.path.relpath(current_path, asset_root), asset)
if pkg_resources.resource_isdir(module, os.path.join(current_path, asset)):
safe_mkdir(os.path.join(output_dir, asset_target))
_unpack_assets(output_dir, module, asset_root, execute, os.path.join(current_path, asset))
else:
output_file = os.path.join(output_dir, asset_target)
with open(output_file, 'wb') as fp:
fp.write(pkg_resources.resource_string(
module, os.path.join(asset_root, asset_target)))
execute(output_file)
示例8: __get_resource_list
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def __get_resource_list(*path_parts):
""" Return the list of elements in a directory based on whether its frozen or not.
Paths parts given should be relative to the pympress package dir.
Args:
name (`tuple` of `str`): The directories that constitute the path to the resource,
relative to the pympress distribution
Returns:
`list` of `str`: The paths to the resources in the directory
"""
if getattr(sys, 'frozen', False):
return os.listdir(os.path.join(os.path.dirname(sys.executable), *path_parts))
else:
req = pkg_resources.Requirement.parse('pympress')
return pkg_resources.resource_listdir(req, '/'.join(('pympress',) + path_parts))
示例9: image_resources
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def image_resources(package=None, directory='resources'):
"""
Returns all images under the directory relative to a package path. If no directory or package is specified then the
resources module of the calling package will be used. Images are recursively discovered.
:param package: package name in dotted format.
:param directory: path relative to package path of the resources directory.
:return: a list of images under the specified resources path.
"""
if not package:
package = calling_package()
package_dir = '.'.join([package, directory])
images = []
for i in resource_listdir(package, directory):
if i.startswith('__') or i.endswith('.egg-info'):
continue
fname = resource_filename(package_dir, i)
if resource_isdir(package_dir, i):
images.extend(image_resources(package_dir, i))
elif what(fname):
images.append(fname)
return images
# etc
示例10: _fuzzdb_get_strings
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_resources.resource_listdir('protofuzz', path)
for filename in listing:
if not filename.endswith('.txt'):
continue
path = '{}/{}/{}'.format(BASE_PATH, subdir, filename)
source = _open_fuzzdb_file(path)
for line in source:
string = line.decode('utf-8').strip()
if not string or string.startswith('#'):
continue
if max_len != 0 and len(line) > max_len:
continue
yield string
示例11: __init__
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def __init__(self, root):
"""
:param root: watchdog base directory
:param reboot_script: reboot script
"""
self.root = root
self.cpu_count = multiprocessing.cpu_count()
self.pid_file = '/var/run/watchdog.pid'
self.config_file = os.path.join(self.root, 'watchdog.conf')
self.script_directory = os.path.join(self.root, 'script')
self.test_directory = os.path.join(self.root, 'watchdog.d')
self.tests = {}
utf8_reader = codecs.getreader('utf8')
test_names = pkg_resources.resource_listdir(
'treadmill', '/etc/kernel_watchdog_tests'
)
for test_name in test_names:
self.tests[test_name] = utf8_reader(
pkg_resources.resource_stream(
'treadmill',
'/etc/kernel_watchdog_tests/{}'.format(test_name)
)
).read()
self.start_command = ['watchdog', '-c', self.config_file, '-b']
示例12: _get_standard_message_registry_collection
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def _get_standard_message_registry_collection(self):
"""Load packaged standard message registries
:returns: list of MessageRegistry
"""
message_registries = []
resource_package_name = __name__
for json_file in pkg_resources.resource_listdir(
resource_package_name, STANDARD_REGISTRY_PATH):
# Not using path.join according to pkg_resources docs
mes_reg = message_registry.MessageRegistry(
None, STANDARD_REGISTRY_PATH + json_file,
reader=base.JsonPackagedFileReader(
resource_package_name))
message_registries.append(mes_reg)
return message_registries
示例13: _stage_transperf_src
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def _stage_transperf_src(tmp=None):
"""Stages transperf src in tmpdir before copy to destination node."""
listfn = lambda: pkg_resources.resource_listdir('transperf', '')
readfn = lambda fname: pkg_resources.resource_string('transperf', fname)
to_sync = []
if tmp is None:
tmp = os.path.join(tempfile.gettempdir(), 'transperf')
if not os.path.exists(tmp):
os.mkdir(tmp)
for f in listfn():
_, ext = os.path.splitext(f)
if ext != '.py':
continue
content = readfn(f)
path = os.path.join(tmp, f)
tempf = open(path, 'w')
tempf.write(content)
tempf.close()
to_sync.append(path)
return tmp, to_sync
示例14: find_components
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def find_components(package, base_class):
"""Find components which are subclass of a given base class.
"""
for filename in resource_listdir(package, ''):
basename, extension = os.path.splitext(filename)
if extension != '.py' or basename.startswith('.'):
continue
module_name = "{}.{}".format(package, basename)
__import__(module_name, fromlist='*')
module = sys.modules[module_name]
if not hasattr(module, '__all__'):
continue
yield from scan_module(module, base_class)
示例15: adjust_settings_paths
# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_listdir [as 別名]
def adjust_settings_paths(self, paths):
base = resource_filename('avocado_vt', 'conf.d')
for path in [os.path.join(base, conf)
for conf in resource_listdir('avocado_vt', 'conf.d')
if conf.endswith('.conf')]:
paths.insert(0, path)