Python posixpath.dirname() Examples

The following are 30 code examples of posixpath.dirname(). 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: lookup.py    From jbox with MIT License 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != '/':
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri)
            else:
                v = self._uri_cache[key] = '/' + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #2
Source File: xmlbuilder.py    From Computable with MIT License 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urlparse
        parts = urlparse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urlparse.urlunparse(parts)

        return source 
Example #3
Source File: xmlbuilder.py    From meddle with MIT License 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urlparse
        parts = urlparse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urlparse.urlunparse(parts)

        return source 
Example #4
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 #5
Source File: xmlbuilder.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urlparse
        parts = urlparse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urlparse.urlunparse(parts)

        return source 
Example #6
Source File: xmlbuilder.py    From BinderFilter with MIT License 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urlparse
        parts = urlparse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urlparse.urlunparse(parts)

        return source 
Example #7
Source File: lookup.py    From teleport with Apache License 2.0 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != "/":
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri
                )
            else:
                v = self._uri_cache[key] = "/" + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #8
Source File: xmlbuilder.py    From oss-ftp with MIT License 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urlparse
        parts = urlparse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urlparse.urlunparse(parts)

        return source 
Example #9
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 #10
Source File: xmlbuilder.py    From jawfish with MIT License 6 votes vote down vote up
def resolveEntity(self, publicId, systemId):
        assert systemId is not None
        source = DOMInputSource()
        source.publicId = publicId
        source.systemId = systemId
        source.byteStream = self._get_opener().open(systemId)

        # determine the encoding if the transport provided it
        source.encoding = self._guess_media_encoding(source)

        # determine the base URI is we can
        import posixpath, urllib.parse
        parts = urllib.parse.urlparse(systemId)
        scheme, netloc, path, params, query, fragment = parts
        # XXX should we check the scheme here as well?
        if path and not path.endswith("/"):
            path = posixpath.dirname(path) + "/"
            parts = scheme, netloc, path, params, query, fragment
            source.baseURI = urllib.parse.urlunparse(parts)

        return source 
Example #11
Source File: lookup.py    From teleport with Apache License 2.0 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != "/":
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri
                )
            else:
                v = self._uri_cache[key] = "/" + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #12
Source File: doctree2md.py    From sphinx-markdown-builder with MIT License 6 votes vote down vote up
def _refuri2http(self, node):
        # Replace 'refuri' in reference with HTTP address, if possible
        # None for no possible address
        url = node.get('refuri')
        if not node.get('internal'):
            return url
        # If HTTP page build URL known, make link relative to that.
        if not self.markdown_http_base:
            return None
        this_doc = self.builder.current_docname
        if url in (None, ''):  # Reference to this doc
            url = self.builder.get_target_uri(this_doc)
        else:  # URL is relative to the current docname.
            this_dir = posixpath.dirname(this_doc)
            if this_dir:
                url = posixpath.normpath('{}/{}'.format(this_dir, url))
        url = '{}/{}'.format(self.markdown_http_base, url)
        if 'refid' in node:
            url += '#' + node['refid']
        return url 
Example #13
Source File: lookup.py    From teleport with Apache License 2.0 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != '/':
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri)
            else:
                v = self._uri_cache[key] = '/' + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #14
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 #15
Source File: relationship.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def get_dependents(archive, filename):
    """
    Normalise dependency file paths to absolute ones

    Relative paths are relative to parent object
    """
    src = archive.read(filename)
    node = fromstring(src)
    rels = RelationshipList.from_tree(node)
    folder = posixpath.dirname(filename)
    parent = posixpath.split(folder)[0]
    for r in rels.Relationship:
        if r.TargetMode == "External":
            continue
        elif r.target.startswith("/"):
            r.target = r.target[1:]
        else:
            pth = posixpath.join(parent, r.target)
            r.target = posixpath.normpath(pth)
    return rels 
Example #16
Source File: lookup.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != "/":
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri
                )
            else:
                v = self._uri_cache[key] = "/" + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #17
Source File: lookup.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def adjust_uri(self, uri, relativeto):
        """Adjust the given ``uri`` based on the given relative URI."""

        key = (uri, relativeto)
        if key in self._uri_cache:
            return self._uri_cache[key]

        if uri[0] != "/":
            if relativeto is not None:
                v = self._uri_cache[key] = posixpath.join(
                    posixpath.dirname(relativeto), uri
                )
            else:
                v = self._uri_cache[key] = "/" + uri
        else:
            v = self._uri_cache[key] = uri
        return v 
Example #18
Source File: test_posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_dirname(self):
        self.assertEqual(posixpath.dirname("/foo/bar"), "/foo")
        self.assertEqual(posixpath.dirname("/"), "/")
        self.assertEqual(posixpath.dirname("foo"), "")
        self.assertEqual(posixpath.dirname("////foo"), "////")
        self.assertEqual(posixpath.dirname("//foo//bar"), "//foo") 
Example #19
Source File: test_posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_realpath_pardir(self):
        self.assertEqual(realpath('..'), dirname(os.getcwd()))
        self.assertEqual(realpath('../..'), dirname(dirname(os.getcwd())))
        self.assertEqual(realpath('/'.join(['..'] * 100)), '/') 
Example #20
Source File: wheel.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_dist_info(self, zf):
        # find the correct name of the .dist-info dir in the wheel file
        for member in zf.namelist():
            dirname = posixpath.dirname(member)
            if (dirname.endswith('.dist-info') and
                    canonicalize_name(dirname).startswith(
                        canonicalize_name(self.project_name))):
                return dirname
        raise ValueError("unsupported wheel format. .dist-info not found") 
Example #21
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 #22
Source File: template.py    From teleport with Apache License 2.0 5 votes vote down vote up
def resolve_path(self, name, parent_path=None):
        if parent_path and not parent_path.startswith("<") and \
            not parent_path.startswith("/") and \
                not name.startswith("/"):
            file_dir = posixpath.dirname(parent_path)
            name = posixpath.normpath(posixpath.join(file_dir, name))
        return name 
Example #23
Source File: template.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def resolve_path(self, name, parent_path=None):
        if parent_path and not parent_path.startswith("<") and \
            not parent_path.startswith("/") and \
                not name.startswith("/"):
            file_dir = posixpath.dirname(parent_path)
            name = posixpath.normpath(posixpath.join(file_dir, name))
        return name 
Example #24
Source File: test_posixpath.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_dirname(self):
        self.assertEqual(posixpath.dirname("/foo/bar"), "/foo")
        self.assertEqual(posixpath.dirname("/"), "/")
        self.assertEqual(posixpath.dirname("foo"), "")
        self.assertEqual(posixpath.dirname("////foo"), "////")
        self.assertEqual(posixpath.dirname("//foo//bar"), "//foo") 
Example #25
Source File: test_posixpath.py    From BinderFilter with MIT License 5 votes vote down vote up
def safe_rmdir(dirname):
    try:
        os.rmdir(dirname)
    except OSError:
        pass 
Example #26
Source File: loader_tags.py    From bioforum with MIT License 5 votes vote down vote up
def construct_relative_path(current_template_name, relative_name):
    """
    Convert a relative path (starting with './' or '../') to the full template
    name based on the current_template_name.
    """
    if not relative_name.startswith(("'./", "'../", '"./', '"../')):
        # relative_name is a variable or a literal that doesn't contain a
        # relative path.
        return relative_name

    new_name = posixpath.normpath(
        posixpath.join(
            posixpath.dirname(current_template_name.lstrip('/')),
            relative_name.strip('\'"')
        )
    )
    if new_name.startswith('../'):
        raise TemplateSyntaxError(
            "The relative path '%s' points outside the file hierarchy that "
            "template '%s' is in." % (relative_name, current_template_name)
        )
    if current_template_name.lstrip('/') == new_name:
        raise TemplateSyntaxError(
            "The relative path '%s' was translated to template name '%s', the "
            "same template in which the tag appears."
            % (relative_name, current_template_name)
        )
    return '"%s"' % new_name 
Example #27
Source File: web.py    From ITWSV with MIT License 5 votes vote down vote up
def parent_dir(self):
        if self.file_name:
            return posixpath.dirname(self._resource_path) + "/"
        elif self.is_root:
            return self._resource_path
        else:
            return posixpath.dirname(posixpath.dirname(self._resource_path)) + "/" 
Example #28
Source File: web.py    From ITWSV with MIT License 5 votes vote down vote up
def dir_name(self):
        if self.file_name:
            return posixpath.dirname(self._resource_path) + "/"
        return self._resource_path 
Example #29
Source File: autohandler.py    From teleport with Apache License 2.0 5 votes vote down vote up
def autohandler(template, context, name='autohandler'):
    lookup = context.lookup
    _template_uri = template.module._template_uri
    if not lookup.filesystem_checks:
        try:
            return lookup._uri_cache[(autohandler, _template_uri, name)]
        except KeyError:
            pass

    tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name]
    while len(tokens):
        path = '/' + '/'.join(tokens)
        if path != _template_uri and _file_exists(lookup, path):
            if not lookup.filesystem_checks:
                return lookup._uri_cache.setdefault(
                    (autohandler, _template_uri, name), path)
            else:
                return path
        if len(tokens) == 1:
            break
        tokens[-2:] = [name]

    if not lookup.filesystem_checks:
        return lookup._uri_cache.setdefault(
            (autohandler, _template_uri, name), None)
    else:
        return None 
Example #30
Source File: template.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def resolve_path(self, name: str, parent_path: str = None) -> str:
        if (
            parent_path
            and not parent_path.startswith("<")
            and not parent_path.startswith("/")
            and not name.startswith("/")
        ):
            file_dir = posixpath.dirname(parent_path)
            name = posixpath.normpath(posixpath.join(file_dir, name))
        return name