Python pkg_resources.resource_string() Examples

The following are 30 code examples of pkg_resources.resource_string(). 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 pkg_resources , or try the search function .
Example #1
Source File: easy_install.py    From jbox with MIT License 7 votes vote down vote up
def get_win_launcher(type):
    """
    Load the Windows launcher (executable) suitable for launching a script.

    `type` should be either 'cli' or 'gui'

    Returns the executable as a byte string.
    """
    launcher_fn = '%s.exe' % type
    if platform.machine().lower() == 'arm':
        launcher_fn = launcher_fn.replace(".", "-arm.")
    if is_64bit():
        launcher_fn = launcher_fn.replace(".", "-64.")
    else:
        launcher_fn = launcher_fn.replace(".", "-32.")
    return resource_string('setuptools', launcher_fn) 
Example #2
Source File: easy_install.py    From oss-ftp with MIT License 6 votes vote down vote up
def get_win_launcher(type):
    """
    Load the Windows launcher (executable) suitable for launching a script.

    `type` should be either 'cli' or 'gui'

    Returns the executable as a byte string.
    """
    launcher_fn = '%s.exe' % type
    if platform.machine().lower() == 'arm':
        launcher_fn = launcher_fn.replace(".", "-arm.")
    if is_64bit():
        launcher_fn = launcher_fn.replace(".", "-64.")
    else:
        launcher_fn = launcher_fn.replace(".", "-32.")
    return resource_string('setuptools', launcher_fn) 
Example #3
Source File: utils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def read_file(filename: str, binary: bool = False) -> typing.Any:
    """Get the contents of a file contained with qutebrowser.

    Args:
        filename: The filename to open as string.
        binary: Whether to return a binary string.
                If False, the data is UTF-8-decoded.

    Return:
        The file contents as string.
    """
    assert not posixpath.isabs(filename), filename
    assert os.path.pardir not in filename.split(posixpath.sep), filename

    if not binary and filename in _resource_cache:
        return _resource_cache[filename]

    if hasattr(sys, 'frozen'):
        # PyInstaller doesn't support pkg_resources :(
        # https://github.com/pyinstaller/pyinstaller/wiki/FAQ#misc
        fn = os.path.join(os.path.dirname(sys.executable), filename)
        if binary:
            with open(fn, 'rb') as f:  # type: typing.IO
                return f.read()
        else:
            with open(fn, 'r', encoding='utf-8') as f:
                return f.read()
    else:
        data = pkg_resources.resource_string(
            qutebrowser.__name__, filename)

        if binary:
            return data

        return data.decode('UTF-8') 
Example #4
Source File: GXDLMSConverter.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def __readStandardObisInfo(cls, standard, codes):
        if standard != Standard.DLMS:
            for it in cls.__getObjects(standard):
                tmp = GXStandardObisCode(it.logicalName.split('.'))
                tmp.interfaces = str(it.objectType)
                tmp.description = it.description
                tmp.uiDataType = it.uiDataType
                codes.append(tmp)

        str_ = pkg_resources.resource_string(__name__, "OBISCodes.txt").decode("utf-8")
        str_ = str_.replace("\n", "\r")
        rows = str_.split('\r')
        for it in rows:
            if it and not it.startswith("#"):
                items = it.split(';')
                obis = items[0].split('.')
                try:
                    code_ = GXStandardObisCode(obis, str(items[3]) + "; " + str(items[4]) + "; " + str(items[5]) + "; " + str(items[6]) + "; " + str(items[7]), str(items[1]), str(items[2]))
                    codes.append(code_)
                except UnicodeEncodeError:
                    pass 
Example #5
Source File: githooks.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def install(client, force):
    """Install Git hooks."""
    warning_messages = []
    for hook in HOOKS:
        hook_path = Path(get_hook_path(hook, client.repo.git_dir))
        if hook_path.exists():
            if not force:
                warning_messages.append(
                    'Hook already exists. Skipping {0}'.format(str(hook_path))
                )
                continue
            else:
                hook_path.unlink()

        # Make sure the hooks directory exists.
        hook_path.parent.mkdir(parents=True, exist_ok=True)

        Path(hook_path).write_bytes(
            pkg_resources.resource_string(
                'renku.data', '{hook}.sh'.format(hook=hook)
            )
        )
        hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)

    return warning_messages 
Example #6
Source File: shacl.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def validate_graph(graph, shacl_path=None, format='nquads'):
    """Validate the current graph with a SHACL schema.

    Uses default schema if not supplied.
    """
    if shacl_path:
        with open(shacl_path, 'r', encoding='utf-8') as f:
            shacl = f.read()
    else:
        shacl = resource_string('renku', 'data/shacl_shape.json')

    return validate(
        graph,
        shacl_graph=shacl,
        inference='rdfs',
        meta_shacl=True,
        debug=False,
        data_graph_format=format,
        shacl_graph_format='json-ld',
        advanced=True
    ) 
Example #7
Source File: eggs.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app_config in apps.get_app_configs():
                try:
                    resource = resource_string(app_config.name, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(self.engine.file_charset)
                return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
        raise TemplateDoesNotExist(template_name) 
Example #8
Source File: __init__.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def load_migration(plugin, filename, module_name=None):
    '''
    Load a migration from its python file

    :returns: the loaded module
    '''
    module_name = module_name or _module_name(plugin)
    basename = os.path.splitext(os.path.basename(filename))[0]
    name = '.'.join((module_name, 'migrations', basename))
    filename = os.path.join('migrations', filename)
    try:
        script = resource_string(module_name, filename)
    except Exception:
        msg = 'Unable to load file {} from module {}'.format(filename, module_name)
        raise MigrationError(msg)
    spec = importlib.util.spec_from_loader(name, loader=None)
    module = importlib.util.module_from_spec(spec)
    exec(script, module.__dict__)
    module.__file__ = resource_filename(module_name, filename)
    return module 
Example #9
Source File: file.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_resource(package, fname):
    """Read the given resource file and return content as string.

    Parameters
    ----------
    package : string
        the package name.
    fname : string
        the resource file name.

    Returns
    -------
    content : unicode
        the content as a unicode string.
    """
    raw_content = pkg_resources.resource_string(package, fname)
    return raw_content.decode(encoding=bag_encoding, errors=bag_codec_error) 
Example #10
Source File: easy_install.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def get_win_launcher(type):
    """
    Load the Windows launcher (executable) suitable for launching a script.

    `type` should be either 'cli' or 'gui'

    Returns the executable as a byte string.
    """
    launcher_fn = '%s.exe' % type
    if platform.machine().lower()=='arm':
        launcher_fn = launcher_fn.replace(".", "-arm.")
    if is_64bit():
        launcher_fn = launcher_fn.replace(".", "-64.")
    else:
        launcher_fn = launcher_fn.replace(".", "-32.")
    return resource_string('setuptools', launcher_fn) 
Example #11
Source File: test_keymanager.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def test_fetch_uses_combined_ca_bundle_otherwise(self):
        with tempfile.NamedTemporaryFile() as tmp_input, \
                tempfile.NamedTemporaryFile(delete=False) as tmp_output:
            ca_content = pkg_resources.resource_string('leap.common.testing',
                                                       'cacert.pem')
            ca_cert_path = tmp_input.name
            self._dump_to_file(ca_cert_path, ca_content)

            pth = 'leap.bitmask.keymanager.tempfile.NamedTemporaryFile'
            with mock.patch(pth) as mocked:
                mocked.return_value = tmp_output
                km = self._key_manager(ca_cert_path=ca_cert_path)
                get_mock = self._mock_get_response(km, PUBLIC_KEY_OTHER)

                yield km.fetch_key(ADDRESS_OTHER, REMOTE_KEY_URL)

                # assert that combined bundle file is passed to get call
                get_mock.assert_called_once_with(REMOTE_KEY_URL, 'GET')

                # assert that files got appended
                expected = self._slurp_file(ca_bundle.where()) + ca_content
                self.assertEqual(expected, self._slurp_file(tmp_output.name)) 
Example #12
Source File: easy_install.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def get_win_launcher(type):
    """
    Load the Windows launcher (executable) suitable for launching a script.

    `type` should be either 'cli' or 'gui'

    Returns the executable as a byte string.
    """
    launcher_fn = '%s.exe' % type
    if platform.machine().lower() == 'arm':
        launcher_fn = launcher_fn.replace(".", "-arm.")
    if is_64bit():
        launcher_fn = launcher_fn.replace(".", "-64.")
    else:
        launcher_fn = launcher_fn.replace(".", "-32.")
    return resource_string('setuptools', launcher_fn) 
Example #13
Source File: cli.py    From autohelm with Apache License 2.0 5 votes vote down vote up
def generate(ctx):
    """ Takes no arguements, outputs an example plan """
    logging.info('Generating exampl course as course.yml')
    src = pkg_resources.resource_string("autohelm", "example-course.yml")
    logging.debug(src)
    with open("./course.yml", "w") as course_file:
        course_file.write(src) 
Example #14
Source File: test_assertrewrite.py    From pytest with MIT License 5 votes vote down vote up
def test_resources_provider_for_loader(self, testdir):
        """
        Attempts to load resources from a package should succeed normally,
        even when the AssertionRewriteHook is used to load the modules.

        See #366 for details.
        """
        pytest.importorskip("pkg_resources")

        testdir.mkpydir("testpkg")
        contents = {
            "testpkg/test_pkg": """
                import pkg_resources

                import pytest
                from _pytest.assertion.rewrite import AssertionRewritingHook

                def test_load_resource():
                    assert isinstance(__loader__, AssertionRewritingHook)
                    res = pkg_resources.resource_string(__name__, 'resource.txt')
                    res = res.decode('ascii')
                    assert res == 'Load me please.'
                """
        }
        testdir.makepyfile(**contents)
        testdir.maketxtfile(**{"testpkg/resource": "Load me please."})

        result = testdir.runpytest_subprocess()
        result.assert_outcomes(passed=1) 
Example #15
Source File: __init__.py    From nekoyume with MIT License 5 votes vote down vote up
def load(self, filename, datacls):
        text = resource_string(
            'nekoyume', os.path.join('tables', filename)
        ).decode('utf-8')
        lines = text.split('\n')
        header = lines[0].split(Table.separator)
        for line in lines[1:]:
            if line:
                data = line.split(Table.separator)
                self[data[0]] = datacls(header, data) 
Example #16
Source File: easy_install.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def load_launcher_manifest(name):
    manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
    if six.PY2:
        return manifest % vars()
    else:
        return manifest.decode('utf-8') % vars() 
Example #17
Source File: nvd_test.py    From vulnix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load(cve):
    return json.loads(pkg_resources.resource_string(
        'vulnix', 'tests/fixtures/{}.json'.format(cve))) 
Example #18
Source File: easy_install.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def get_win_launcher(type):
    """
    Load the Windows launcher (executable) suitable for launching a script.

    `type` should be either 'cli' or 'gui'

    Returns the executable as a byte string.
    """
    launcher_fn = '%s.exe' % type
    if is_64bit():
        launcher_fn = launcher_fn.replace(".", "-64.")
    else:
        launcher_fn = launcher_fn.replace(".", "-32.")
    return resource_string('setuptools', launcher_fn) 
Example #19
Source File: easy_install.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def install_site_py(self):
        """Make sure there's a site.py in the target dir, if needed"""

        if self.sitepy_installed:
            return  # already did it, or don't need to

        sitepy = os.path.join(self.install_dir, "site.py")
        source = resource_string("setuptools", "site-patch.py")
        source = source.decode('utf-8')
        current = ""

        if os.path.exists(sitepy):
            log.debug("Checking existing site.py in %s", self.install_dir)
            with io.open(sitepy) as strm:
                current = strm.read()

            if not current.startswith('def __boot():'):
                raise DistutilsError(
                    "%s is not a setuptools-generated site.py; please"
                    " remove it." % sitepy
                )

        if current != source:
            log.info("Creating %s", sitepy)
            if not self.dry_run:
                ensure_directory(sitepy)
                with io.open(sitepy, 'w', encoding='utf-8') as strm:
                    strm.write(source)
            self.byte_compile([sitepy])

        self.sitepy_installed = True 
Example #20
Source File: GXDLMSConverter.py    From Gurux.DLMS.Python with GNU General Public License v2.0 5 votes vote down vote up
def __getObjects(cls, standard):
        codes = list()
        if standard == Standard.ITALY:
            str_ = pkg_resources.resource_string(__name__, "Italy.txt").decode("utf-8")
        elif standard == Standard.INDIA:
            str_ = pkg_resources.resource_string(__name__, "India.txt").decode("utf-8")
        elif standard == Standard.SAUDI_ARABIA:
            str_ = pkg_resources.resource_string(__name__, "SaudiArabia.txt").decode("utf-8")
        if not str_:
            return None
        str_ = str_.replace("\n", "\r")
        rows = str_.split('\r')
        for it in rows:
            if it and not it.startswith("#"):
                items = it.split(';')
                if len(items) > 1:
                    ot = int(items[0])
                    ln = _GXCommon.toLogicalName(_GXCommon.logicalNameToBytes(items[1]))
                    version = int(items[2])
                    desc = items[3]
                    code_ = GXObisCode(ln, ot, 0, desc)
                    code_.version = version
                    if len(items) > 4:
                        code_.uiDataType = items[4]
                    codes.append(code_)
        return codes 
Example #21
Source File: easy_install.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _load_template(dev_path):
        """
        There are a couple of template scripts in the package. This
        function loads one of them and prepares it for use.
        """
        # See https://github.com/pypa/setuptools/issues/134 for info
        # on script file naming and downstream issues with SVR4
        name = 'script.tmpl'
        if dev_path:
            name = name.replace('.tmpl', ' (dev).tmpl')

        raw_bytes = resource_string('setuptools', name)
        return raw_bytes.decode('utf-8') 
Example #22
Source File: test_fingerprint.py    From roca with MIT License 5 votes vote down vote up
def _get_res(self, name):
        """
        Loads resource
        :param name:
        :return:
        """
        resource_package = __name__
        resource_path = '/'.join(('data', name))
        return pkg_resources.resource_string(resource_package, resource_path) 
Example #23
Source File: __main__.py    From coverage-badge with MIT License 5 votes vote down vote up
def get_badge(total, color=DEFAULT_COLOR):
    """
    Read the SVG template from the package, update total, return SVG as a
    string.
    """
    template_path = os.path.join('templates', 'flat.svg')
    template = pkg_resources.resource_string(__name__, template_path).decode('utf8')
    return template.replace('{{ total }}', total).replace('{{ color }}', color) 
Example #24
Source File: easy_install.py    From oss-ftp with MIT License 5 votes vote down vote up
def load_launcher_manifest(name):
    manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
    if PY2:
        return manifest % vars()
    else:
        return manifest.decode('utf-8') % vars() 
Example #25
Source File: vulnerability_test.py    From vulnix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load(cve):
    return json.loads(pkg_resources.resource_string(
        'vulnix', 'tests/fixtures/{}.json'.format(cve))) 
Example #26
Source File: easy_install.py    From oss-ftp with MIT License 5 votes vote down vote up
def install_site_py(self):
        """Make sure there's a site.py in the target dir, if needed"""

        if self.sitepy_installed:
            return  # already did it, or don't need to

        sitepy = os.path.join(self.install_dir, "site.py")
        source = resource_string("setuptools", "site-patch.py")
        current = ""

        if os.path.exists(sitepy):
            log.debug("Checking existing site.py in %s", self.install_dir)
            f = open(sitepy, 'rb')
            current = f.read()
            # we want str, not bytes
            if PY3:
                current = current.decode()

            f.close()
            if not current.startswith('def __boot():'):
                raise DistutilsError(
                    "%s is not a setuptools-generated site.py; please"
                    " remove it." % sitepy
                )

        if current != source:
            log.info("Creating %s", sitepy)
            if not self.dry_run:
                ensure_directory(sitepy)
                f = open(sitepy, 'wb')
                f.write(source)
                f.close()
            self.byte_compile([sitepy])

        self.sitepy_installed = True 
Example #27
Source File: easy_install.py    From oss-ftp with MIT License 5 votes vote down vote up
def _load_template(dev_path):
        """
        There are a couple of template scripts in the package. This
        function loads one of them and prepares it for use.
        """
        # See https://bitbucket.org/pypa/setuptools/issue/134 for info
        # on script file naming and downstream issues with SVR4
        name = 'script.tmpl'
        if dev_path:
            name = name.replace('.tmpl', ' (dev).tmpl')

        raw_bytes = resource_string('setuptools', name)
        return raw_bytes.decode('utf-8') 
Example #28
Source File: resources.py    From cloudformation-environmentbase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_resource(resource_name, relative_to_module_name=__name__):
    """
    Retrieves resource embedded in the package (even if installed as a zipped archive).
    """
    file_path = test_resource('data', resource_name, relative_to_module_name)
    file_content = resource_string(relative_to_module_name, file_path)
    return file_content 
Example #29
Source File: __init__.py    From BreezyCreate2 with MIT License 5 votes vote down vote up
def load(self):
        """ Loads a Create2 config file, that holds various dicts of opcodes.
        
        """
        self.data = json.loads(pkg_resources.resource_string('breezycreate2', self.fname).decode('utf8')) 
Example #30
Source File: config.py    From wallpaper-reddit with GNU General Public License v3.0 5 votes vote down vote up
def init_config():
    global walldir
    global confdir
    if opsys == "Windows":
        walldir = os.path.expanduser("~/Wallpaper-Reddit")
        confdir = os.path.expanduser("~/Wallpaper-Reddit/config")
    else:
        walldir = os.path.expanduser("~/.wallpaper")
        confdir = os.path.expanduser("~/.config/wallpaper-reddit")
    if not os.path.exists(walldir):
        os.makedirs(walldir)
        log(walldir + " created")
    if not os.path.exists(walldir + '/blacklist.txt'):
        with open(walldir + '/blacklist.txt', 'w') as blacklist:
            blacklist.write('')
    if not os.path.exists(walldir + '/url.txt'):
        with open(walldir + '/url.txt', 'w') as urlfile:
            urlfile.write('')
    if not os.path.exists(walldir + '/fonts'):
        os.makedirs(walldir + '/fonts')
    if not os.path.exists(walldir + '/fonts/Cantarell-Regular.otf'):
        with open(walldir + '/fonts/Cantarell-Regular.otf', 'wb') as font:
            font.write(resource_string(__name__, 'fonts/Cantarell-Regular.otf'))
    if not os.path.exists(confdir):
        os.makedirs(confdir)
        log(confdir + " created")
    if not os.path.isfile(confdir + '/wallpaper-reddit.conf'):
        if opsys == 'Windows':
            cfile = resource_string(__name__, 'conf_files/windows.conf')
        else:
            cfile = resource_string(__name__, 'conf_files/unix.conf')
        with open(confdir + '/wallpaper-reddit.conf', 'wb') as f:
            f.write(cfile)
    parse_config()
    parse_args()
    log("config and args parsed")


# reads the configuration at ~/.config/wallpaper-reddit