当前位置: 首页>>代码示例>>Python>>正文


Python Requirement.parse方法代码示例

本文整理汇总了Python中pkg_resources.Requirement.parse方法的典型用法代码示例。如果您正苦于以下问题:Python Requirement.parse方法的具体用法?Python Requirement.parse怎么用?Python Requirement.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pkg_resources.Requirement的用法示例。


在下文中一共展示了Requirement.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setUp

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [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

示例2: _init_entry_point

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def _init_entry_point(self, entry_point):
        if not entry_point.dist:
            logger.warning(
                'entry_points passed to %s for registration must provide a '
                'distribution with a project name; registration of %s skipped',
                cls_to_name(type(self)), entry_point,
            )
            return
        key = entry_point.dist.project_name
        self.records.setdefault(key, [])
        # have to cast the entry point into
        try:
            requirement = Requirement.parse(str(entry_point).split('=', 1)[1])
        except ValueError as e:
            logger.warning(
                "entry_point '%s' cannot be registered to %s due to the "
                "following error: %s",
                entry_point, cls_to_name(type(self)), e
            )
        else:
            self.records[key].append(requirement) 
开发者ID:calmjs,项目名称:calmjs,代码行数:23,代码来源:toolchain.py

示例3: transpile_modname_source_target

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def transpile_modname_source_target(self, spec, modname, source, target):
        """
        The function that gets called by compile_transpile_entry for
        processing the provided JavaScript source file provided by some
        Python package through the transpiler instance.
        """

        if not isinstance(self.transpiler, BaseUnparser):
            _deprecation_warning(
                'transpiler callable assigned to %r must be an instance of '
                'calmjs.parse.unparsers.base.BaseUnparser by calmjs-4.0.0; '
                'if the original transpile behavior is to be retained, the '
                'subclass may instead override this method to call '
                '`simple_transpile_modname_source_target` directly, as '
                'this fallback behavior will be removed by calmjs-4.0.0' % (
                    self,
                )
            )
            return self.simple_transpile_modname_source_target(
                spec, modname, source, target)

        # do the new thing here.
        return self._transpile_modname_source_target(
            spec, modname, source, target) 
开发者ID:calmjs,项目名称:calmjs,代码行数:26,代码来源:toolchain.py

示例4: matches_requirement

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def matches_requirement(req, wheels):
    """List of wheels matching a requirement.

    :param req: The requirement to satisfy
    :param wheels: List of wheels to search.
    """
    try:
        from pkg_resources import Distribution, Requirement
    except ImportError:
        raise RuntimeError("Cannot use requirements without pkg_resources")

    req = Requirement.parse(req)

    selected = []
    for wf in wheels:
        f = wf.parsed_filename
        dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
        if dist in req:
            selected.append(wf)
    return selected 
开发者ID:jpush,项目名称:jbox,代码行数:22,代码来源:util.py

示例5: find_egg_info_file

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def find_egg_info_file(self, pattern=''):
        """
        Find pip metadata files in unpacked source distributions.

        When pip unpacks a source distribution archive it creates a directory
        ``pip-egg-info`` which contains the package metadata in a declarative
        and easy to parse format. This method finds such metadata files.

        :param pattern: The :mod:`glob` pattern to search for (a string).
        :returns: A list of matched filenames (strings).
        """
        full_pattern = os.path.join(self.requirement.source_directory, 'pip-egg-info', '*.egg-info', pattern)
        logger.debug("Looking for %r file(s) using pattern %r ..", pattern, full_pattern)
        matches = glob.glob(full_pattern)
        if len(matches) > 1:
            msg = "Source distribution directory of %s (%s) contains multiple *.egg-info directories: %s"
            raise Exception(msg % (self.requirement.project_name, self.requirement.version, concatenate(matches)))
        elif matches:
            logger.debug("Matched %s: %s.", pluralize(len(matches), "file", "files"), concatenate(matches))
            return matches[0]
        else:
            logger.debug("No matching %r files found.", pattern) 
开发者ID:paylogic,项目名称:py2deb,代码行数:24,代码来源:package.py

示例6: initial_checks

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def initial_checks(template=None, facemask=None):
    """Initial sanity checks."""
    if template is None:
        template = resource_filename(Requirement.parse("pydeface"),
                                     "pydeface/data/mean_reg2mean.nii.gz")
    if facemask is None:
        facemask = resource_filename(Requirement.parse("pydeface"),
                                     "pydeface/data/facemask.nii.gz")

    if not os.path.exists(template):
        raise Exception('Missing template: %s' % template)
    if not os.path.exists(facemask):
        raise Exception('Missing face mask: %s' % facemask)

    if 'FSLDIR' not in os.environ:
        raise Exception("FSL must be installed and "
                        "FSLDIR environment variable must be defined.")
        sys.exit(2)
    return template, facemask 
开发者ID:poldracklab,项目名称:pydeface,代码行数:21,代码来源:utils.py

示例7: clean_requires_python

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def clean_requires_python(candidates):
    """Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
    all_candidates = []
    sys_version = ".".join(map(str, sys.version_info[:3]))
    from packaging.version import parse as parse_version

    py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
    for c in candidates:
        requires_python = _get_requires_python(c)
        if requires_python:
            # Old specifications had people setting this to single digits
            # which is effectively the same as '>=digit,<digit+1'
            if requires_python.isdigit():
                requires_python = ">={0},<{1}".format(
                    requires_python, int(requires_python) + 1
                )
            try:
                specifierset = SpecifierSet(requires_python)
            except InvalidSpecifier:
                continue
            else:
                if not specifierset.contains(py_version):
                    continue
        all_candidates.append(c)
    return all_candidates 
开发者ID:pypa,项目名称:pipenv,代码行数:27,代码来源:utils.py

示例8: _get_config_file

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def _get_config_file(config_path):
        """
        Load the content of the config file. If no config_path is specified, get the default of config file.

        :param config_path: path to the config file or None
        :returns: the content of the config file
        """
        try:
            if not config_path:
                config_path = resource_filename(Requirement.parse('checkQC'), 'checkQC/default_config/config.yaml')
                log.info("No config file specified, using default config from {}.".format(config_path))

            with open(config_path) as stream:
                return yaml.load(stream)
        except FileNotFoundError as e:
            log.error("Could not find config file: {}".format(e))
            raise e 
开发者ID:Molmed,项目名称:checkQC,代码行数:19,代码来源:config.py

示例9: get_logging_config_dict

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def get_logging_config_dict(config_path):
        """
        Loads the specified logger config. This is useful when CheckQC is used more like a library, so that the
        default logging configuration can be overridden.

        :param config_path: Path to the logging config.
        :returns: The content of the logging config file.
        """
        try:
            if not config_path:
                config_path = resource_filename(Requirement.parse('checkQC'), 'checkQC/default_config/logger.yaml')
                log.info("No logging config file specified, using default config from {}.".format(config_path))
            with open(config_path) as stream:
                return yaml.load(stream)
        except FileNotFoundError as e:
            log.error("Could not find config file: {}".format(e))
            raise e 
开发者ID:Molmed,项目名称:checkQC,代码行数:19,代码来源:config.py

示例10: get_templates_dir

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def get_templates_dir():
    res_dir = None
    try:
        # this will fail when not in a distribution
        res_dir = resource_filename(Requirement.parse("ambassador"), "templates")
    except:
        pass

    maybe_dirs = [
        res_dir,
        os.path.join(os.path.dirname(__file__), "..", "templates")
    ]
    for d in maybe_dirs:
        if d and os.path.isdir(d):
            return d
    raise FileNotFoundError


# Get the Flask app defined early. Setup happens later. 
开发者ID:datawire,项目名称:ambassador,代码行数:21,代码来源:diagd.py

示例11: get_jsonschema_validator

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def get_jsonschema_validator(self, apiVersion, kind) -> Optional[Validator]:
        # Do we have a JSONSchema on disk for this?
        schema_path = os.path.join(self.schema_dir_path, apiVersion, f"{kind}.schema")

        try:
            schema = json.load(open(schema_path, "r"))

            # Note that we'll never get here if the schema doesn't parse.
            if schema:
                self.logger.debug(f"using validate_with_jsonschema for getambassador.io/{apiVersion} {kind}")

                # Ew. Early binding for Python lambdas is kinda weird.
                return typecast(Validator,
                                lambda resource, schema=schema: self.validate_with_jsonschema(resource, schema))
        except OSError:
            self.logger.debug(f"no schema at {schema_path}, not validating")
            return None
        except json.decoder.JSONDecodeError as e:
            self.logger.warning(f"corrupt schema at {schema_path}, skipping ({e})")
            return None

        # This can't actually happen -- the only way to get here is to have an uncaught
        # exception. But it shuts up mypy so WTF.
        return None 
开发者ID:datawire,项目名称:ambassador,代码行数:26,代码来源:config.py

示例12: create

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def create():
    parser = argparse.ArgumentParser(description='Create a new NetWrok server.')
    parser.add_argument("name", help="The name of the new netwrok instance.")
    parser.add_argument("dsn", help="Connection string to an empty PostgreSQL database.")
    args = parser.parse_args()
    print("Connecting to: " + args.dsn)
    try:
        conn = psycopg2.connect(args.dsn)
    except Exception as e:
        print(e)
        return
    sql_file = resource_filename(Requirement.parse("NetWrok-Server"),"netwrok/data/schema.sql")
    print("Creating new DB schema...")
    cursor = conn.cursor()
    cursor.execute("begin")
    cursor.execute(open(sql_file, "r").read())
    config["DB"]["WRITE"] = args.dsn
    config["DB"]["READ"] = [args.dsn,args.dsn,args.dsn]
    new_config_file = "netwrok_%s.ini"%args.name
    print("Writing config file to: %s"%new_config_file)
    with open(new_config_file, "w") as nf:
        json.dump(config, nf, sort_keys=True, indent=4, separators=(',', ': '))
    cursor.execute("commit")
    cursor.close()
    print("You can now start the server with 'netwrok %s'"%new_config_file) 
开发者ID:simonwittber,项目名称:netwrok-server,代码行数:27,代码来源:cmd.py

示例13: make_ecc_interpolant

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def make_ecc_interpolant():

    """
    Make interpolation function from eccentricity file to
    determine number of harmonics to use for a given
    eccentricity.

    :returns: interpolant
    """

    pth = resource_filename(Requirement.parse("libstempo"), "libstempo/ecc_vs_nharm.txt")

    fil = np.loadtxt(pth)

    return interp1d(fil[:, 0], fil[:, 1])


# get interpolant for eccentric binaries 
开发者ID:nanograv,项目名称:enterprise,代码行数:20,代码来源:utils.py

示例14: command_parse

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def command_parse(self, args):
        if not self.initialised:
            self.initialised = self._init_haros_dir(overwrite=False)
        if args.data_dir and not os.path.isdir(args.data_dir):
            raise ValueError("Not a directory: " + args.data_dir)
        project_file = args.project_file or self.index_path
        if not os.path.isfile(project_file):
            raise ValueError("Not a file: " + project_file)
        if args.ws:
            if not os.path.isdir(args.ws):
                raise ValueError("Not a directory: " + args.ws)
        parse = HarosParseRunner(self.haros_dir, self.config_path,
            project_file, args.data_dir, log=self.log,
            run_from_source=self.run_from_source, use_repos=args.use_repos,
            ws=args.ws, copy_env=args.env, use_cache=(not args.no_cache),
            junit_xml_output=args.junit_xml_output,
            minimal_output=args.minimal_output)
        return parse.run() 
开发者ID:git-afsantos,项目名称:haros,代码行数:20,代码来源:haros.py

示例15: parse_arguments

# 需要导入模块: from pkg_resources import Requirement [as 别名]
# 或者: from pkg_resources.Requirement import parse [as 别名]
def parse_arguments(self, argv = None):
        parser = ArgumentParser(prog = "haros",
                                description = "ROS quality assurance.")
        parser.add_argument("--home",
                            help=("HAROS data and config directory (default: "
                                  + self.haros_dir))
        parser.add_argument("--config",
                            help=("HAROS config location (default: "
                                  + self.haros_dir + "configs.yaml"))
        parser.add_argument("--debug", action = "store_true",
                            help = "set debug logging")
        parser.add_argument("-c", "--cwd",
                            help = "change current directory before running")
        subparsers = parser.add_subparsers()
        self._init_parser(subparsers.add_parser("init"))
        self._full_parser(subparsers.add_parser("full"))
        self._analyse_parser(subparsers.add_parser("analyse"))
        self._export_parser(subparsers.add_parser("export"))
        self._viz_parser(subparsers.add_parser("viz"))
        self._parse_parser(subparsers.add_parser("parse"))
        return parser.parse_args(argv) 
开发者ID:git-afsantos,项目名称:haros,代码行数:23,代码来源:haros.py


注:本文中的pkg_resources.Requirement.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。