Python posixpath.basename() Examples

The following are 30 code examples of posixpath.basename(). 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 posixpath , or try the search function .
Example #1
Source File: wsgi.py    From lambda-packs with MIT License 6 votes vote down vote up
def get_package_loader(self, package, package_path):
        from pkg_resources import DefaultProvider, ResourceManager, \
            get_provider
        loadtime = datetime.utcnow()
        provider = get_provider(package)
        manager = ResourceManager()
        filesystem_bound = isinstance(provider, DefaultProvider)

        def loader(path):
            if path is None:
                return None, None
            path = posixpath.join(package_path, path)
            if not provider.has_resource(path):
                return None, None
            basename = posixpath.basename(path)
            if filesystem_bound:
                return basename, self._opener(
                    provider.get_resource_filename(manager, path))
            s = provider.get_resource_string(manager, path)
            return basename, lambda: (
                BytesIO(s),
                loadtime,
                len(s)
            )
        return loader 
Example #2
Source File: urlutils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def filename_from_url(url: QUrl) -> typing.Optional[str]:
    """Get a suitable filename from a URL.

    Args:
        url: The URL to parse, as a QUrl.

    Return:
        The suggested filename as a string, or None.
    """
    if not url.isValid():
        return None
    pathname = posixpath.basename(url.path())
    if pathname:
        return pathname
    elif url.host():
        return url.host() + '.html'
    else:
        return None 
Example #3
Source File: test_posixpath.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                os.chdir(dirname(ABSTFN))

                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example #4
Source File: test_posixpath.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                with support.change_cwd(dirname(ABSTFN)):
                    base = basename(ABSTFN)
                    self.assertEqual(realpath(base + "link"), ABSTFN)
                    self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                test_support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example #5
Source File: test_posixpath.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_realpath_resolve_before_normalizing(self):
            # Bug #990669: Symbolic links should be resolved before we
            # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
            # in the following hierarchy:
            # a/k/y
            #
            # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
            # then realpath("link-y/..") should return 'k', not 'a'.
            try:
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.mkdir(ABSTFN + "/k/y")
                os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

                # Absolute path.
                self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
                # Relative path.
                with support.change_cwd(dirname(ABSTFN)):
                    self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                     ABSTFN + "/k")
            finally:
                test_support.unlink(ABSTFN + "/link-y")
                safe_rmdir(ABSTFN + "/k/y")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example #6
Source File: test_posixpath.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                os.chdir(dirname(ABSTFN))

                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example #7
Source File: index.py    From oss-ftp with MIT License 6 votes vote down vote up
def _find_url_name(self, index_url, url_name, req):
        """Finds the true URL name of a package, when the given name isn't quite correct.
        This is usually used to implement case-insensitivity."""
        if not index_url.url.endswith('/'):
            # Vaguely part of the PyPI API... weird but true.
            ## FIXME: bad to modify this?
            index_url.url += '/'
        page = self._get_page(index_url, req)
        if page is None:
            logger.fatal('Cannot fetch index base URL %s' % index_url)
            return
        norm_name = normalize_name(req.url_name)
        for link in page.links:
            base = posixpath.basename(link.path.rstrip('/'))
            if norm_name == normalize_name(base):
                logger.notify('Real name of requirement %s is %s' % (url_name, base))
                return base
        return None 
Example #8
Source File: wsgi.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def get_package_loader(self, package, package_path):
        from pkg_resources import DefaultProvider, ResourceManager, \
            get_provider
        loadtime = datetime.utcnow()
        provider = get_provider(package)
        manager = ResourceManager()
        filesystem_bound = isinstance(provider, DefaultProvider)

        def loader(path):
            if path is None:
                return None, None
            path = posixpath.join(package_path, path)
            if not provider.has_resource(path):
                return None, None
            basename = posixpath.basename(path)
            if filesystem_bound:
                return basename, self._opener(
                    provider.get_resource_filename(manager, path))
            s = provider.get_resource_string(manager, path)
            return basename, lambda: (
                BytesIO(s),
                loadtime,
                len(s)
            )
        return loader 
Example #9
Source File: index.py    From oss-ftp with MIT License 5 votes vote down vote up
def filename(self):
        _, netloc, path, _, _ = urlparse.urlsplit(self.url)
        name = posixpath.basename(path.rstrip('/')) or netloc
        assert name, ('URL %r produced no filename' % self.url)
        return name 
Example #10
Source File: index.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def filename(self):
        _, netloc, path, _, _ = urllib_parse.urlsplit(self.url)
        name = posixpath.basename(path.rstrip('/')) or netloc
        name = urllib_parse.unquote(name)
        assert name, ('URL %r produced no filename' % self.url)
        return name 
Example #11
Source File: index.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def splitext(self):
        return splitext(posixpath.basename(self.path.rstrip('/'))) 
Example #12
Source File: index.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) 
Example #13
Source File: test_posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_realpath_symlink_loops(self):
            # Bug #930024, return the path unchanged if we get into an infinite
            # symlink loop.
            try:
                old_path = abspath('.')
                os.symlink(ABSTFN, ABSTFN)
                self.assertEqual(realpath(ABSTFN), ABSTFN)

                os.symlink(ABSTFN+"1", ABSTFN+"2")
                os.symlink(ABSTFN+"2", ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")

                self.assertEqual(realpath(ABSTFN+"1/x"), ABSTFN+"1/x")
                self.assertEqual(realpath(ABSTFN+"1/.."), dirname(ABSTFN))
                self.assertEqual(realpath(ABSTFN+"1/../x"), dirname(ABSTFN) + "/x")
                os.symlink(ABSTFN+"x", ABSTFN+"y")
                self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "y"),
                                ABSTFN + "y")
                self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "1"),
                                ABSTFN + "1")

                os.symlink(basename(ABSTFN) + "a/b", ABSTFN+"a")
                self.assertEqual(realpath(ABSTFN+"a"), ABSTFN+"a/b")

                os.symlink("../" + basename(dirname(ABSTFN)) + "/" +
                        basename(ABSTFN) + "c", ABSTFN+"c")
                self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c")

                # Test using relative path as well.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN)
                test_support.unlink(ABSTFN+"1")
                test_support.unlink(ABSTFN+"2")
                test_support.unlink(ABSTFN+"y")
                test_support.unlink(ABSTFN+"c")
                test_support.unlink(ABSTFN+"a") 
Example #14
Source File: locators.py    From oss-ftp with MIT License 5 votes vote down vote up
def score_url(self, url):
        """
        Give an url a score which can be used to choose preferred URLs
        for a given project release.
        """
        t = urlparse(url)
        return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
                posixpath.basename(t.path)) 
Example #15
Source File: link.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def filename(self):
        # type: () -> str
        _, netloc, path, _, _ = urllib_parse.urlsplit(self.url)
        name = posixpath.basename(path.rstrip('/')) or netloc
        name = urllib_parse.unquote(name)
        assert name, ('URL %r produced no filename' % self.url)
        return name 
Example #16
Source File: index.py    From oss-ftp with MIT License 5 votes vote down vote up
def splitext(self):
        return splitext(posixpath.basename(self.path.rstrip('/'))) 
Example #17
Source File: index.py    From oss-ftp with MIT License 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) 
Example #18
Source File: test_posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_realpath_resolve_before_normalizing(self):
            # Bug #990669: Symbolic links should be resolved before we
            # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
            # in the following hierarchy:
            # a/k/y
            #
            # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
            # then realpath("link-y/..") should return 'k', not 'a'.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.mkdir(ABSTFN + "/k/y")
                os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

                # Absolute path.
                self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
                # Relative path.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                 ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "/link-y")
                safe_rmdir(ABSTFN + "/k/y")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example #19
Source File: index.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) 
Example #20
Source File: locators.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def score_url(self, url):
        """
        Give an url a score which can be used to choose preferred URLs
        for a given project release.
        """
        t = urlparse(url)
        basename = posixpath.basename(t.path)
        compatible = True
        is_wheel = basename.endswith('.whl')
        is_downloadable = basename.endswith(self.downloadable_extensions)
        if is_wheel:
            compatible = is_compatible(Wheel(basename), self.wheel_tags)
        return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
                is_downloadable, is_wheel, compatible, basename) 
Example #21
Source File: index.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) 
Example #22
Source File: index.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def splitext(self):
        return splitext(posixpath.basename(self.path.rstrip('/'))) 
Example #23
Source File: index.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def filename(self):
        _, netloc, path, _, _ = urllib_parse.urlsplit(self.url)
        name = posixpath.basename(path.rstrip('/')) or netloc
        name = urllib_parse.unquote(name)
        assert name, ('URL %r produced no filename' % self.url)
        return name 
Example #24
Source File: locators.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def score_url(self, url):
        """
        Give an url a score which can be used to choose preferred URLs
        for a given project release.
        """
        t = urlparse(url)
        basename = posixpath.basename(t.path)
        compatible = True
        is_wheel = basename.endswith('.whl')
        if is_wheel:
            compatible = is_compatible(Wheel(basename), self.wheel_tags)
        return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
                is_wheel, compatible, basename) 
Example #25
Source File: images.py    From idunn with Apache License 2.0 5 votes vote down vote up
def get_url_remote_thumbnail(
        self, source, width=0, height=0, bestFit=True, progressive=False, animated=False
    ):
        displayErrorImage = False

        salt = self.get_salt()
        token = f"{source}{width}x{height}{salt}"
        hash = hashlib.sha256(bytes(token, encoding="utf8")).hexdigest()
        base_url = self.get_thumbr_url(hash)

        size = f"{width}x{height}"
        hashURLpart = f"{hash[0]}/{hash[1]}/{hash[2:]}"

        url_path = urlsplit(source).path
        filename = posixpath.basename(unquote(url_path))
        if not bool(re.match(r"^.*\.(jpg|jpeg|png|gif)$", filename, re.IGNORECASE)):
            filename += ".jpg"

        params = urllib.parse.urlencode(
            {
                "u": source,
                "q": 1 if displayErrorImage else 0,
                "b": 1 if bestFit else 0,
                "p": 1 if progressive else 0,
                "a": 1 if animated else 0,
            }
        )
        return base_url + "/" + size + "/" + hashURLpart + "/" + filename + "?" + params 
Example #26
Source File: index.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) 
Example #27
Source File: index.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def splitext(self):
        return splitext(posixpath.basename(self.path.rstrip('/'))) 
Example #28
Source File: index.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def filename(self):
        _, netloc, path, _, _ = urllib_parse.urlsplit(self.url)
        name = posixpath.basename(path.rstrip('/')) or netloc
        name = urllib_parse.unquote(name)
        assert name, ('URL %r produced no filename' % self.url)
        return name 
Example #29
Source File: locators.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def score_url(self, url):
        """
        Give an url a score which can be used to choose preferred URLs
        for a given project release.
        """
        t = urlparse(url)
        basename = posixpath.basename(t.path)
        compatible = True
        is_wheel = basename.endswith('.whl')
        if is_wheel:
            compatible = is_compatible(Wheel(basename), self.wheel_tags)
        return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
                is_wheel, compatible, basename) 
Example #30
Source File: index.py    From Python24 with MIT License 5 votes vote down vote up
def show_url(self):
        return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0])