當前位置: 首頁>>代碼示例>>Python>>正文


Python pkg_resources.resource_listdir方法代碼示例

本文整理匯總了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 
開發者ID:wwood,項目名稱:singlem,代碼行數:26,代碼來源:singlem.py

示例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 
開發者ID:hyperledger,項目名稱:aries-cloudagent-python,代碼行數:19,代碼來源:classloader.py

示例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) 
開發者ID:glennmatthews,項目名稱:cot,代碼行數:19,代碼來源:install_helpers.py

示例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 
開發者ID:SwissDataScienceCenter,項目名稱:renku-python,代碼行數:19,代碼來源:migrate.py

示例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) 
開發者ID:cityjson,項目名稱:cjio,代碼行數:24,代碼來源:cityjson.py

示例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] 
開發者ID:mdomke,項目名稱:schwifty,代碼行數:22,代碼來源:registry.py

示例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) 
開發者ID:apache,項目名稱:incubator-retired-cotton,代碼行數:18,代碼來源:pkgutil.py

示例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)) 
開發者ID:Cimbali,項目名稱:pympress,代碼行數:19,代碼來源:util.py

示例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 
開發者ID:redcanari,項目名稱:canari3,代碼行數:27,代碼來源:resource.py

示例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 
開發者ID:trailofbits,項目名稱:protofuzz,代碼行數:27,代碼來源:values.py

示例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'] 
開發者ID:Morgan-Stanley,項目名稱:treadmill,代碼行數:26,代碼來源:kernel_watchdog.py

示例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 
開發者ID:openstack,項目名稱:sushy,代碼行數:20,代碼來源:main.py

示例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 
開發者ID:google,項目名稱:transperf,代碼行數:24,代碼來源:launch.py

示例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) 
開發者ID:maxking,項目名稱:paper-to-git,代碼行數:15,代碼來源:modules.py

示例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) 
開發者ID:avocado-framework,項目名稱:avocado-vt,代碼行數:8,代碼來源:vt_settings.py


注:本文中的pkg_resources.resource_listdir方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。