Python importlib_resources.path() Examples

The following are 12 code examples of importlib_resources.path(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module importlib_resources , or try the search function .
Example #1
Source File: create.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def _expand_template(template_file, data, output_file):
    output = StringIO()
    interpreter = em.Interpreter(
        output=output,
        options={
            em.BUFFERED_OPT: True,
            em.RAW_OPT: True,
        },
        globals=data,
    )
    with open(template_file, 'r') as h:
        try:
            interpreter.file(h)
            content = output.getvalue()
        except Exception as e:
            if os.path.exists(output_file):
                os.remove(output_file)
            print("Exception when expanding '%s' into '%s': %s" %
                  (template_file, output_file, e), file=sys.stderr)
            raise
        finally:
            interpreter.shutdown()

    if os.path.exists(output_file):
        with open(output_file, 'r') as h:
            if h.read() == content:
                return
    else:
        os.makedirs(os.path.dirname(output_file), exist_ok=True)

    with open(output_file, 'w') as h:
        h.write(content) 
Example #2
Source File: create.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def _create_folder(folder_name, base_directory, exist_ok=True):
    folder_path = os.path.join(base_directory, folder_name)

    print('creating folder', folder_path)
    os.makedirs(folder_path, exist_ok=exist_ok)

    return folder_path 
Example #3
Source File: create.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def _create_template_file(
    template_subdir, template_file_name, output_directory, output_file_name, template_config
):
    full_package = 'ros2pkg.resource.' + template_subdir
    with importlib_resources.path(full_package, template_file_name) as path:
        template_path = str(path)
    if not os.path.exists(template_path):
        raise FileNotFoundError('template not found:', template_path)

    output_file_path = os.path.join(output_directory, output_file_name)

    print('creating', output_file_path)
    _expand_template(template_path, template_config, output_file_path) 
Example #4
Source File: test_path.py    From pipenv with MIT License 5 votes vote down vote up
def execute(self, package, path):
        with resources.path(package, path):
            pass 
Example #5
Source File: test_path.py    From pipenv with MIT License 5 votes vote down vote up
def test_reading(self):
        # Path should be readable.
        # Test also implicitly verifies the returned object is a pathlib.Path
        # instance.
        with resources.path(self.data, 'utf-8.file') as path:
            self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
            # pathlib.Path.read_text() was introduced in Python 3.5.
            with path.open('r', encoding='utf-8') as file:
                text = file.read()
            self.assertEqual('Hello, UTF-8 world!\n', text) 
Example #6
Source File: test_path.py    From pipenv with MIT License 5 votes vote down vote up
def test_remove_in_context_manager(self):
        # It is not an error if the file that was temporarily stashed on the
        # file system is removed inside the `with` stanza.
        with resources.path(self.data, 'utf-8.file') as path:
            path.unlink() 
Example #7
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_errors(self):
        errors = self._parser.error_log
        return [
            ValidationDetail(None, err.line, err.column, err.domain_name,
                             err.type_name, err.message, err.path)
            for err in errors
        ] 
Example #8
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def load(self, schema_type):
        path = self._build_path(schema_type)
        return self._parse(path) 
Example #9
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_path(self, schema_type):
        filename = self._schema_files[schema_type]
        with importlib_resources.path(self._import_path, filename) as path:
            return path 
Example #10
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _parse(path):
        xmlschema_doc = etree.parse(str(path))
        return etree.XMLSchema(xmlschema_doc) 
Example #11
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_errors(error_log):
        return [
            ValidationDetail(None, err.line, err.column, err.domain_name,
                             err.type_name, _strip_namespaces(err.message), err.path)
            for err in error_log
        ] 
Example #12
Source File: cve.py    From RVD with GNU General Public License v3.0 4 votes vote down vote up
def cve_jsonvalidation(json_doc_path, version, mode="public"):
    """
    Validate CVE JSON format

    :param json_doc_path string, absolute path for the
    :returns bool
    """
    # fetch from official repository
    if version == 4:
        if mode == "public":
            os.system(
                "mkdir -p /tmp/cve; cd /tmp/cve/ ; \
                wget https://raw.githubusercontent.com/CVEProject/\
automation-working-group/master/cve_json_schema/CVE_JSON_4.0_min_public.schema"
            )
            schema_path = "/tmp/cve/CVE_JSON_4.0_min_public.schema"
        elif mode == "reject":
            os.system(
                "mkdir -p /tmp/cve; cd /tmp/cve/ ; \
                wget https://raw.githubusercontent.com/CVEProject/\
automation-working-group/master/cve_json_schema/CVE_JSON_4.0_min_reject.schema"
            )
            schema_path = "/tmp/cve/CVE_JSON_4.0_min_reject.schema"
        elif mode == "reserved":
            os.system(
                "mkdir -p /tmp/cve; cd /tmp/cve/ ; \
                wget https://raw.githubusercontent.com/CVEProject/\
automation-working-group/master/cve_json_schema/CVE_JSON_4.0_min_reserved.schema"
            )
            schema_path = "/tmp/cve/CVE_JSON_4.0_min_reserved.schema"
        else:
            print("Mode " + mode + "not implemented")
            raise NotImplementedError
    elif version == 3:
        raise NotImplementedError
    else:
        print("Invalid version")
        raise SystemExit

    # via a file, e.g.
    with open(schema_path, "r") as schema:
        schema_doc = json.load(schema)

    # Open the file for reading
    with open(json_doc_path, "r") as document:
        try:
            json_doc = json.load(document)
        except ValueError as err:
            sys.stderr.write("Failed to parse JSON : \n")
            sys.stderr.write("  " + str(err) + "\n")
            raise SystemExit

    try:
        validate(json_doc, schema_doc)
        green("Record passed validation \n")
    except jsonschema.exceptions.ValidationError as incorrect:
        validator = Draft4Validator(schema_doc)
        errors = sorted(validator.iter_errors(json_doc), key=lambda e: e.path)
        for error in errors:
            red("Record did not pass: \n")
            sys.stderr.write(str(error.message) + "\n")