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


Python pkg_resources.resource_filename方法代碼示例

本文整理匯總了Python中pkg_resources.resource_filename方法的典型用法代碼示例。如果您正苦於以下問題:Python pkg_resources.resource_filename方法的具體用法?Python pkg_resources.resource_filename怎麽用?Python pkg_resources.resource_filename使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pkg_resources的用法示例。


在下文中一共展示了pkg_resources.resource_filename方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _test_validate

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def _test_validate(self, schema, expect_failure, input_files, input):
        """validates input yaml against schema.

        :param schema: schema yaml file
        :param expect_failure: should the validation pass or fail.
        :param input_files: pytest fixture used to access the test input files
        :param input: test input yaml doc filename"""
        schema_dir = pkg_resources.resource_filename('drydock_provisioner',
                                                     'schemas')
        schema_filename = os.path.join(schema_dir, schema)
        schema_file = open(schema_filename, 'r')
        schema = yaml.safe_load(schema_file)

        input_file = input_files.join(input)
        instance_file = open(str(input_file), 'r')
        instance = yaml.safe_load(instance_file)

        if expect_failure:
            with pytest.raises(ValidationError):
                jsonschema.validate(instance['spec'], schema['data'])
        else:
            jsonschema.validate(instance['spec'], schema['data']) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:24,代碼來源:test_schema_validation.py

示例2: setUp

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def setUp(self):
    file_path = resource_filename(Requirement.parse('google_streetview'), 'google_streetview/config.json')
    with open(file_path, 'r') as in_file:
      defaults = json.load(in_file)
    params = [{
      'size': '600x300', # max 640x640 pixels
      'location': '46.414382,10.013988',
      'heading': '151.78',
      'pitch': '-0.76',
      'key': defaults['key']
    }]
    self.results = google_streetview.api.results(params)
    tempfile = TemporaryFile()
    self.tempfile = str(tempfile.name)
    tempfile.close()
    self.tempdir = str(TemporaryDirectory().name) 
開發者ID:rrwen,項目名稱:google_streetview,代碼行數:18,代碼來源:test_api_results.py

示例3: validate

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def validate(ctx):
    """
    Validate the paradrop.yaml file.

    A note about versions: this command validates the chute configuration
    against the current rules for the installed version of pdtools. If
    the chute is to be installed on a Paradrop node running a different
    version, then this command may not be reliable for determining
    compatibility.
    """
    with open('paradrop.yaml', 'r') as source:
        chute = yaml.safe_load(source)

    schema_path = pkg_resources.resource_filename('pdtools', 'schemas/chute.json')
    with open(schema_path, 'r') as source:
        schema = json.load(source)

    validator = jsonschema.Draft4Validator(schema)
    for error in sorted(validator.iter_errors(chute), key=str):
        click.echo(error.message) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:22,代碼來源:chute.py

示例4: test_identifier_extract_unusual

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def test_identifier_extract_unusual(self):
        answers = [
            '\'"\'',
            '\'\"\'',
            "\'\"\'",
            "\n",
            "\t",
            r'\\ ',
            "\u3042",
            "\u3042",
            "    ",
        ]
        with open(resource_filename('calmjs.testing', join(
                'names', 'unusual.js')), encoding='utf-8') as fd:
            tree = es5(fd.read())
        for obj_node, answer in zip(interrogate.shallow_filter(
                tree, lambda node: isinstance(node, Object)), answers):
            self.assertEqual(answer, interrogate.to_identifier(
                obj_node.properties[0].left)) 
開發者ID:calmjs,項目名稱:calmjs,代碼行數:21,代碼來源:test_interrogate.py

示例5: load_app

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def load_app(conf, not_implemented_middleware=True):
    global APPCONFIGS

    # Build the WSGI app
    cfg_path = conf.api.paste_config
    if not os.path.isabs(cfg_path):
        cfg_path = conf.find_file(cfg_path)

    if cfg_path is None or not os.path.exists(cfg_path):
        LOG.debug("No api-paste configuration file found! Using default.")
        cfg_path = os.path.abspath(pkg_resources.resource_filename(
            __name__, "api-paste.ini"))

    config = dict(conf=conf,
                  not_implemented_middleware=not_implemented_middleware)
    configkey = str(uuid.uuid4())
    APPCONFIGS[configkey] = config

    LOG.info("WSGI config used: %s", cfg_path)

    appname = "gnocchi+" + conf.api.auth_mode
    app = deploy.loadapp("config:" + cfg_path, name=appname,
                         global_conf={'configkey': configkey})
    return http_proxy_to_wsgi.HTTPProxyToWSGI(
        cors.CORS(app, conf=conf), conf=conf) 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:27,代碼來源:app.py

示例6: __init__

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def __init__(self, benign_path=None, malicious_path=None,
                 model_path=pkg_resources.resource_filename('mmbot', 'model'), retain_sample_contents=False):
        """
        Constructor to setup path variables for model and sample data and initialize object.
        :param benign_path: directory path (relative or absolute) to benign documents for the machine learning model to learn from.
        :param malicious_path: directory path (relative or absolute) to malicious documents for the machine learning model to learn from.
        :param model_path: directory where modeldata.pickle and vocab.txt files are kept.
        :param retain_sample_contents: this relates to level of detail saved in the model data.  If True, potentially sensitive
        information like extracted vba will be stored in the model's pickle file.  The benefit is that incremental
        models can be built, where adding a new file to the training set will result in only reprocessing that one new
        file.  Otherwise all files in the benign_path and malicious_path will be reprocessed each time the model is
        rebuilt.  If you are experimenting with building many models and comparing results, set this to True,
        otherwise keep it to False.
        """
        # os.path.join(os.path.dirname(__file__), 'model')
        self.clear_state()
        self.set_model_paths(benign_path, malicious_path, model_path)
        self.retain_sample_contents = retain_sample_contents 
開發者ID:egaus,項目名稱:MaliciousMacroBot,代碼行數:20,代碼來源:mmbot.py

示例7: load_services

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def load_services(services):
    for service in services:
        service_plugins[service] = {}

        service_config = cf.config('config:' + service)
        if service_config is None:
            logger.error("Service `%s' has no config section" % service)
            sys.exit(1)

        service_plugins[service]['config'] = service_config

        module = cf.g('config:' + service, 'module', service)
        modulefile = resource_filename('mqttwarn.services', module + '.py')

        try:
            service_plugins[service]['module'] = load_module(modulefile)
            logger.info('Successfully loaded service "{}"'.format(service))
        except Exception as ex:
            logger.exception('Unable to load service "{}" from file "{}": {}'.format(service, modulefile, ex)) 
開發者ID:jpmens,項目名稱:mqttwarn,代碼行數:21,代碼來源:core.py

示例8: run_pearl_bash

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def run_pearl_bash(
        script: str, pearl_env,
        capture_stdout: bool = False, capture_stderr: bool = False,
        check: bool = True,
        input: str = None,
        enable_xtrace: bool = False,
        enable_errexit: bool = True,
):
    """Runs a bash script within the Pearl ecosystem."""

    bash_header = _BASH_SCRIPT_HEADER_TEMPLATE.format(
        pearlhome=pearl_env.home,
        static=pkg_resources.resource_filename('pearllib', 'static/'),
    )
    script_template = '{bashheader}\nset -x\n{script}' if enable_xtrace else '{bashheader}\n{script}'
    if enable_errexit:
        script_template = 'set -e\n{}'.format(script_template)

    script = script_template.format(
        bashheader=bash_header,
        script=script,
    )
    return run_bash(script, capture_stdout=capture_stdout, capture_stderr=capture_stderr, check=check, input=input) 
開發者ID:pearl-core,項目名稱:pearl,代碼行數:25,代碼來源:utils.py

示例9: create_package

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def create_package(pearl_env: PearlEnvironment, args: Namespace):
    """
    Creates package from template.
    """
    static = Path(pkg_resources.resource_filename('pearllib', 'static/'))
    pearl_config_template = static / 'templates/pearl-config.template'
    dest_pearl_config = args.dest_dir / 'pearl-config'
    if dest_pearl_config.exists():
        raise PackageCreateError('The pearl-config directory already exists in {}'.format(args.dest_dir))
    shutil.copytree(str(pearl_config_template), str(dest_pearl_config))

    messenger.info('Updating {} to add package in local repository...'.format(pearl_env.config_filename))
    with pearl_env.config_filename.open('a') as pearl_conf_file:
        pearl_conf_file.write('PEARL_PACKAGES["{}"] = {{"url": "{}"}}\n'.format(args.name, args.dest_dir))

    messenger.info('Run "pearl search local" to see your new local package available') 
開發者ID:pearl-core,項目名稱:pearl,代碼行數:18,代碼來源:package.py

示例10: git_changed_submodules

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def git_changed_submodules(git_rev='HEAD@{1}', stop_rev=None, git_root='.'):
    if stop_rev is not None:
        git_rev = "{0}..{1}".format(git_rev, stop_rev)
    diff_script = pkg_resources.resource_filename('conda_concourse_ci', 'diff-script.sh')

    diff = subprocess.check_output(['bash', diff_script, git_rev],
                                    cwd=git_root, universal_newlines=True)

    submodule_changed_files = [line.split() for line in diff.splitlines()]

    submodules_with_recipe_changes = []
    for submodule in submodule_changed_files:
        for file in submodule:
            if 'recipe/' in file and submodule[0] not in submodules_with_recipe_changes:
                submodules_with_recipe_changes.append(submodule[0])

    return submodules_with_recipe_changes 
開發者ID:conda-forge,項目名稱:staged-recipes,代碼行數:19,代碼來源:compute_build_graph.py

示例11: test_pydist

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def test_pydist():
    """Make sure pydist.json exists and validates against our schema."""
    # XXX this test may need manual cleanup of older wheels

    import jsonschema

    def open_json(filename):
        return json.loads(open(filename, 'rb').read().decode('utf-8'))

    pymeta_schema = open_json(resource_filename('wheel.test',
                                                'pydist-schema.json'))
    valid = 0
    for dist in ("simple.dist", "complex-dist"):
        basedir = pkg_resources.resource_filename('wheel.test', dist)
        for (dirname, subdirs, filenames) in os.walk(basedir):
            for filename in filenames:
                if filename.endswith('.whl'):
                    whl = ZipFile(os.path.join(dirname, filename))
                    for entry in whl.infolist():
                        if entry.filename.endswith('/metadata.json'):
                            pymeta = json.loads(whl.read(entry).decode('utf-8'))
                            jsonschema.validate(pymeta, pymeta_schema)
                            valid += 1
    assert valid > 0, "No metadata.json found" 
開發者ID:jpush,項目名稱:jbox,代碼行數:26,代碼來源:test_basic.py

示例12: get_outputnode_spec

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def get_outputnode_spec():
    """
    Generate outputnode's fields from I/O spec file.

    Examples
    --------
    >>> get_outputnode_spec()  # doctest: +NORMALIZE_WHITESPACE
    ['t1w_preproc', 't1w_mask', 't1w_dseg', 't1w_tpms',
    'std_preproc', 'std_mask', 'std_dseg', 'std_tpms',
    'anat2std_xfm', 'std2anat_xfm',
    't1w_aseg', 't1w_aparc',
    't1w2fsnative_xfm', 'fsnative2t1w_xfm',
    'surfaces']

    """
    spec = loads(Path(pkgrf('smriprep', 'data/io_spec.json')).read_text())["queries"]
    fields = ['_'.join((m, s)) for m in ('t1w', 'std') for s in spec["baseline"].keys()]
    fields += [s for s in spec["std_xfms"].keys()]
    fields += [s for s in spec["surfaces"].keys()]
    return fields 
開發者ID:nipreps,項目名稱:smriprep,代碼行數:22,代碼來源:bids.py

示例13: frost

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def frost(x, severity=1):
    c = [(1, 0.4),
         (0.8, 0.6),
         (0.7, 0.7),
         (0.65, 0.7),
         (0.6, 0.75)][severity - 1]
    idx = np.random.randint(5)
    filename = [resource_filename(__name__, 'frost/frost1.png'),
                resource_filename(__name__, 'frost/frost2.png'),
                resource_filename(__name__, 'frost/frost3.png'),
                resource_filename(__name__, 'frost/frost4.jpg'),
                resource_filename(__name__, 'frost/frost5.jpg'),
                resource_filename(__name__, 'frost/frost6.jpg')][idx]
    frost = cv2.imread(filename)
    # randomly crop and convert to rgb
    x_start, y_start = np.random.randint(0, frost.shape[0] - 224), np.random.randint(0, frost.shape[1] - 224)
    frost = frost[x_start:x_start + 224, y_start:y_start + 224][..., [2, 1, 0]]

    return np.clip(c[0] * np.array(x) + c[1] * frost, 0, 255) 
開發者ID:hendrycks,項目名稱:robustness,代碼行數:21,代碼來源:corruptions.py

示例14: _get_schema_dir

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def _get_schema_dir(self):
        return pkg_resources.resource_filename('drydock_provisioner',
                                               'schemas')

    # Mapping of handlers for different document kinds 
開發者ID:airshipit,項目名稱:drydock,代碼行數:7,代碼來源:deckhand.py

示例15: __init__

# 需要導入模塊: import pkg_resources [as 別名]
# 或者: from pkg_resources import resource_filename [as 別名]
def __init__(self):
        self.__default_gen_file = resource_filename("cisco.bass.avclass", 'default.generics')
        self.__default_alias_file = resource_filename("cisco.bass.avclass", 'default.aliases')
        self.__default_category_file = resource_filename("cisco.bass.avclass", 'default.categories') 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:6,代碼來源:avclass.py


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