• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python posixpath.relpath函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中posixpath.relpath函数的典型用法代码示例。如果您正苦于以下问题:Python relpath函数的具体用法?Python relpath怎么用?Python relpath使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: main

def main():
    chapter_files, other_files = get_filenames()

    # make previous of first file and next of last file to just bring
    # back to README
    prevs = ['README.md'] + chapter_files[:-1]
    nexts = chapter_files[1:] + ['README.md']

    print("Chapter files:")
    for prevpath, thispath, nextpath in zip(prevs, chapter_files, nexts):
        # all paths should be like 'section/file.md'
        where = posixpath.dirname(thispath)
        prev = posixpath.relpath(prevpath, where)
        next_ = posixpath.relpath(nextpath, where)
        extralinks = "[Previous](%s) | [Next](%s) |\n" % (prev, next_)
        end = END_TEMPLATE.format(
            toplevel='..', extralinks=extralinks, readmeheader=where)
        update_end(thispath, end)

    print()

    print("Other files:")
    for filename in other_files:
        where = posixpath.dirname(filename)
        end = END_TEMPLATE.format(
            toplevel=posixpath.relpath('.', where),
            extralinks="", readmeheader='list-of-contents')
        update_end(filename, end)
开发者ID:Akuli,项目名称:python-tutorial,代码行数:28,代码来源:update-ends.py


示例2: __iter__

    def __iter__(self):
        for item in self.previous:
            yield item

        cwd = os.getcwd()
        yield {self.pathkey: posixpath.sep,
               self.typekey: self.foldertype}

        try:
            os.chdir(self.dirname)
            for (dirpath, dirnames, filenames) in os.walk(os.curdir):
                os.chdir(cwd)

                # Convert path from os.path to posixpath
                dirpath = posixpath.join(*pathsplit(dirpath, ospath=os.path))

                def sortkey(basename, dirpath=dirpath, sortkey=self.sortkey):
                    return sortkey({}, dirpath=dirpath, basename=basename)

                for basename in sorted(filenames, key=sortkey):
                    yield {self.pathkey: posixpath.relpath(
                        posixpath.join(posixpath.sep, dirpath, basename),
                        posixpath.sep)}
                for basename in sorted(dirnames, key=sortkey):
                    yield {
                        self.pathkey: posixpath.relpath(
                            posixpath.join(posixpath.sep, dirpath, basename),
                            posixpath.sep) + posixpath.sep,
                        self.typekey: self.foldertype}

                os.chdir(self.dirname)

        finally:
            os.chdir(cwd)
开发者ID:datakurre,项目名称:collective.transmogrifier,代码行数:34,代码来源:dirwalker.py


示例3: scan

    def scan(self):
        if not self.fs:
            self.attachFileSystem(self.basepath)
        
        self._dirs = dict()
        self._files = dict()

        for root, _dirs, _files in self.fs.walk(self.fs.basepath):
            for _dir in _dirs:
                path = os.path.join(root, _dir).replace("\\", "/")
                
                stat = self.fs.stat(path)

                path = posixpath.relpath(path, self.fs.basepath)

                self._dirs[path] = {
                    "size": stat.st_size,
                    "mdate": stat.st_mtime
                }

            for _file in _files:
                path = os.path.join(root, _file).replace("\\", "/")

                stat = self.fs.stat(path)

                path = posixpath.relpath(path, self.fs.basepath)

                self._files[path] = {
                    "size": stat.st_size,
                    "mdate": stat.st_mtime
                }
        
        return self
开发者ID:rotoclap,项目名称:sync,代码行数:33,代码来源:sync.py


示例4: run

    def run(self):
        # MOE needs to be invoked from the directory containing the SVL scripts, otherwise it can't seem to
        # "find" the other SVL files. It would be nice to eliminate this issue and use absolute paths.
        #lex = shlex.shlex(
        #    'moe -load "{script}" -exec "HomologyBatch [\'{input}\']"'.format(
        #        script=self.args['svl_script_name'],  # The file will be accessed from the parent dir.
        #        # MOE only accepts POSIX-like file paths as SVL function arguments.
        #        input=posixpath.relpath(self.args['input_directory'], start=self.args['svl_directory'])
        #    )
        #)
        #lex.whitespace_split = True
        #process_args = list(lex)
        #check_call(process_args, stdout=PIPE, cwd=self.args['svl_directory'])

        process_args = 'moebatch -run "{script}" -options "{options}" -template "{template}" -sequence "{sequence}" -out "{outDir}"'.format(
            script=self.args['svl_script_name'],  # The file will be accessed from the parent dir.
            options=posixpath.relpath(self.args['homology_options'], start=self.args['svl_directory']),
            template=posixpath.relpath(self.args['template_file'], start=self.args['svl_directory']),
            sequence=posixpath.relpath(self.args['sequence_file'], start=self.args['svl_directory']),
            outDir=posixpath.relpath(self.args['outputDir'], start=self.args['svl_directory'])
        )
        try:
            # This script currently outputs the homology model files in the directory where it was invoked.
            # Call the script from the output directory.
            check_call(process_args, stdout=PIPE, shell=True, cwd=self.args['svl_directory'])
        except CalledProcessError as e:
            # For some reason, moebatch seems to always return 1.
            if e.returncode != 1:  # Ignore a return code of 1.
                raise e
开发者ID:Cjsheaf,项目名称:Variation-Discovery-Pipeline,代码行数:29,代码来源:Homology_Modeling.py


示例5: diff

 def diff(self, relative = False):
     (d, f) = self.scan()
     ef = f - self.__of
     mf = self.__of - f
     ed = d - self.__od
     md = self.__od - d
     if relative:
         ef = set([posixpath.relpath(x, self.__path) for x in ef])
         mf = set([posixpath.relpath(x, self.__path) for x in mf])
         ed = set([posixpath.relpath(x, self.__path) for x in ed])
         md = set([posixpath.relpath(x, self.__path) for x in md])
     return ed, ef, md, mf
开发者ID:litaoshao,项目名称:python-mirbuild,代码行数:12,代码来源:test_cmake.py


示例6: lookup_redirect

        def lookup_redirect(url):
            sub_url = url

            for sub_url, _ in Segment(url):
                for base, filename in Segment(sub_url):
                    try:
                        redirects = self._cache.GetFromFile(
                            posixpath.normpath(posixpath.join(base, "redirects.json"))
                        ).Get()
                    except FileNotFoundError:
                        continue

                    redirect = redirects.get(posixpath.join(filename, "..."))

                    if redirect is None:
                        continue

                    redirect = Join(base, redirect.rstrip("..."))

                    # Avoid infinite redirection loops by breaking if seen before.
                    if redirect in seen_redirects:
                        break
                    seen_redirects.add(redirect)
                    return lookup_redirect(Join(redirect, posixpath.relpath(url, sub_url)))
            return url
开发者ID:kjthegod,项目名称:chromium,代码行数:25,代码来源:redirector.py


示例7: get_relative_url

def get_relative_url(destination, source):
    """Get relative URL between two sources.

    http://stackoverflow.com/a/7469668/315168

    :param destination:
    :param source:
    :return: tuple (is same domain, relative url)
    """

    u_dest = urlparse.urlsplit(destination)
    u_src = urlparse.urlsplit(source)

    _uc1 = urlparse.urlunsplit(u_dest[:2]+tuple('' for i in range(3)))
    _uc2 = urlparse.urlunsplit(u_src[:2]+tuple('' for i in range(3)))

    if _uc1 != _uc2:
        ## This is a different domain
        return False, destination

    # If there is no / component in url assume it's root path
    src_path = u_src.path or "/"

    _relpath = posixpath.relpath(u_dest.path, posixpath.dirname(src_path))

    return True, _relpath
    # return True, urlparse.urlunsplit(('', '', _relpath, u_dest.query, u_dest.fragment))
开发者ID:kiok46,项目名称:webkivy,代码行数:27,代码来源:relurl.py


示例8: make_relative

 def make_relative(self, url):
     """
     Given a URL path return it as a relative URL,
     given the context of the current page.
     """
     suffix = '/' if (url.endswith('/') and len(url) > 1) else ''
     return posixpath.relpath(url, start=self.base_path) + suffix
开发者ID:OlderWoo,项目名称:hiloteam.github.io,代码行数:7,代码来源:nav.py


示例9: _apply_regex_rule

    def _apply_regex_rule(self, rule_name, rule, cat_name, cat_path, settings):
        accepted_flags = {
            'a': re.ASCII,
            'i': re.IGNORECASE,
            'l': re.LOCALE,
            'x': re.VERBOSE
        }
        flags = sum([accepted_flags[f] for f in rule.get('flags', [])])

        pattern = None
        try:
            pattern = re.compile(rule['pattern'], flags)
        except KeyError:
            raise InvalidRegexFilter(cat_name, rule_name)

        actions = []

        rename = rule.get('rename', None)
        for root, dirs, files in os.walk(self._path):
            if posixpath.abspath(root) == self._repo_path:
                continue

            for file_name in files:
                file_name = posixpath.relpath(posixpath.join(root, file_name), self._path)

                match = pattern.match(file_name)
                if match:
                    new_name = file_name
                    if rename:
                        new_name = rename.format(**match.groupdict())

                    new_name = posixpath.join(cat_path, new_name)
                    actions.append(('mv', posixpath.join(self._path, file_name), new_name))

        return actions
开发者ID:asgeir,项目名称:old-school-projects,代码行数:35,代码来源:repository.py


示例10: get_path_components

 def get_path_components(self, relative_to=None):
     if relative_to:
         if not isinstance(relative_to, FTPFile):
             raise ValueError("relative_to must be another FTPFile "
                              "instance")
         return posixpath.relpath(self._path, relative_to._path).split("/")
     return self._path.split("/")
开发者ID:javawizard,项目名称:fileutils,代码行数:7,代码来源:ftp.py


示例11: makeNodesRelative

def makeNodesRelative(nodes, knobTypes):
    result = { 'warnings': [], 'replacements': [], 'projectFolder': None}
    projectfile = nuke.root()['name'].value() 
    if projectfile =="":
        result['warnings'].append('Please save the nuke script before running this function such that it has a valid path.')
        return result
    projectFolderAbsolute = posixpath.dirname(projectfile)
    result['projectFolder'] = projectFolderAbsolute
    projectFolderRelative = "[file dirname [value root.name]]"

    for n in nodes:
        for k in knobTypes:
            if n.knob(k):
                originalFilePath = n[k].value()
                if n[k].isAnimated():
                    result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since the knob is animated')
                elif n[k].hasExpression():
                    result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since the knob has an expression')
                elif originalFilePath.strip()=="":
                    #result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since it is empty')
                    pass
                elif originalFilePath.startswith(projectFolderRelative): 
                    result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since it is already a relative path:\n'+ __removePrefix(originalFilePath,projectFolderRelative))
                else:
                    relativeFilePath =  posixpath.relpath(originalFilePath,projectFolderAbsolute)
                    n[k].setValue(projectFolderRelative + '/' +relativeFilePath)
                    result['replacements'].append(k+' of '+ n['name'].value()+':\n'+relativeFilePath)
                        
    return result
开发者ID:weijer,项目名称:NukeToolSet,代码行数:29,代码来源:relativeFilePath.py


示例12: get_jottapath

def get_jottapath(localtopdir, dirpath, jottamountpoint):
    """Translate localtopdir to jottapath. Returns unicode string"""
    log.debug("get_jottapath %r %r %r", localtopdir, dirpath, jottamountpoint)
    normpath = posixpath.normpath(
        posixpath.join(jottamountpoint, posixpath.basename(localtopdir), posixpath.relpath(dirpath, localtopdir))
    )
    return _decode_filename_to_unicode(normpath)
开发者ID:havardgulldahl,项目名称:jottalib,代码行数:7,代码来源:jottacloud.py


示例13: _get_relative_path

    def _get_relative_path(a, b):
        """
        returns a relative path for navigation from dir *a* to dir *b*

        if the common parent of both is "/", return an absolute path
        """
        a += "/"
        b += "/"
        parent = posixpath.dirname(posixpath.commonprefix([a,b]))
        if parent == "/": return b[:-1]

        a = posixpath.relpath(a, parent)
        b = posixpath.relpath(b, parent)
        if a == ".": return b

        return posixpath.normpath("../" * (a.count("/")+1) + b)
开发者ID:asobolev,项目名称:python-odml,代码行数:16,代码来源:base.py


示例14: get_url

def get_url(current, target):
    current = urlparse(current).path
    target = urlparse(target).path

    result = posixpath.relpath(target, current).split('/')
    result = '/'.join(result[1:])
    return result
开发者ID:mfussenegger,项目名称:riccodo,代码行数:7,代码来源:riccodo.py


示例15: recursive_copy

def recursive_copy(sourcefs, targetfs, sourcepath, targetpath):
    #normalise paths
    norm_sourcepath = posixpath.normpath(sourcepath)
    norm_targetpath = posixpath.normpath(targetpath)
    
    #Create the first directory in the target file system if it does not already exist
    source_end_path = posixpath.split(posixpath.normpath(sourcepath))[1]
   
    #if the target path exists, make a new directory into the target path directory
    if targetfs.exists(norm_targetpath):
        base_target_path = posixpath.normpath(posixpath.join(norm_targetpath, source_end_path)) 
    #if the target does not exist but its parent does, rename the directory and copy
    elif targetfs.exists(posixpath.normpath(posixpath.join(norm_targetpath, ".."))):
        #If it does not exist, create that directory
        base_target_path = norm_targetpath
    else:
        raise IOError("Cannot copy into target: "+targetpath)

    if not targetfs.exists(base_target_path):
        targetfs.mkdir(base_target_path)
              
    for (path, directories, files) in sourcefs.walk(norm_sourcepath):
        rel_source_path = posixpath.relpath(path, norm_sourcepath)
        new_target_path = posixpath.normpath(posixpath.join(base_target_path, rel_source_path))
        print new_target_path
        for f in files:
            copy_file_into_directory(sourcefs, targetfs, posixpath.join(path, f), new_target_path)
        for d in directories:
            new_directory = posixpath.join(new_target_path, d)
            if not targetfs.exists(new_directory):
                targetfs.mkdir(new_directory)
开发者ID:joskoetsier,项目名称:rapidomero,代码行数:31,代码来源:operations.py


示例16: path2tag

def path2tag(rootpath, pathname):
    """Convert a pathname to a tagname.

    Normalizes the path before converting to a tagname.

    """
    return '//' + posixpath.relpath(pathname, rootpath)
开发者ID:darkfeline,项目名称:dantalian,代码行数:7,代码来源:tagnames.py


示例17: listdir

    def listdir(self, name):
        path = self._normalize_name(self._clean_name(name))
        # The path needs to end with a slash, but if the root is empty, leave
        # it.
        if path and not path.endswith('/'):
            path += '/'

        directories = []
        files = []
        paginator = self.connection.meta.client.get_paginator('list_objects')
        pages = paginator.paginate(Bucket=self.bucket_name, Delimiter='/', Prefix=path)
        for page in pages:
            for entry in page.get('CommonPrefixes', ()):
                directories.append(posixpath.relpath(entry['Prefix'], path))
            for entry in page.get('Contents', ()):
                files.append(posixpath.relpath(entry['Key'], path))
        return directories, files
开发者ID:jschneier,项目名称:django-storages,代码行数:17,代码来源:s3boto3.py


示例18: __repo_for_path

 def __repo_for_path(self, path):
     path_prefixes = sorted(self.uri.keys(), key=lambda x: len(x), reverse=True)
     for prefix in path_prefixes:
         if path.startswith(prefix):
             relpath = posixpath.relpath(path, prefix or '.') if path else ''
             return prefix, self.uri[prefix], relpath if relpath != '.' else None
     raise ValueError(("No KnowledgeRepository found for '{}', "
                       "paths must be prefixed with {}.").format(path, path_prefixes))
开发者ID:WangLaoK,项目名称:knowledge-repo,代码行数:8,代码来源:meta.py


示例19: relative_url

def relative_url(target, base):
    base = urlparse.urlparse(base)
    target = urlparse.urlparse(target)
    if base.netloc != target.netloc:
        raise ValueError('target and base netlocs do not match')
    base_dir = '.' + posixpath.dirname(base.path)
    target = '.' + target.path
    return '/' + posixpath.relpath(target, start=base_dir)
开发者ID:reydelamirienda,项目名称:nuevo,代码行数:8,代码来源:engine.py


示例20: __target_relpath

 def __target_relpath(self):
     # workaround for posixpath bug in 2.6, doesn't generate correct
     # relative path when *start* (second) parameter is root ('/')
     if self.__baseURI == '/':
         relpath = self.target.partname[1:]
     else:
         relpath = posixpath.relpath(self.target.partname, self.__baseURI)
     return relpath
开发者ID:dixon-che,项目名称:python-pptx,代码行数:8,代码来源:packaging.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python posixpath.samefile函数代码示例发布时间:2022-05-25
下一篇:
Python posixpath.realpath函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap