当前位置: 首页>>代码示例>>Python>>正文


Python path.relpath方法代码示例

本文整理汇总了Python中os.path.relpath方法的典型用法代码示例。如果您正苦于以下问题:Python path.relpath方法的具体用法?Python path.relpath怎么用?Python path.relpath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os.path的用法示例。


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

示例1: _walk_moler_python_files

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def _walk_moler_python_files(path, *args):
    """
    Walk thru directory with commands and search for python source code (except __init__.py)
    Yield relative filepath to parameter path

    :param path: relative path do directory with commands
    :type path:
    :rtype: str
    """
    repo_path = abspath(join(path, '..', '..'))

    observer = "event" if "events" in split(path) else "command"
    print("Processing {}s test from path: '{}'".format(observer, path))

    for (dirpath, _, filenames) in walk(path):
        for filename in filenames:
            if filename.endswith('__init__.py'):
                continue
            if filename.endswith('.py'):
                abs_path = join(dirpath, filename)
                in_moler_path = relpath(abs_path, repo_path)
                yield in_moler_path 
开发者ID:nokia,项目名称:moler,代码行数:24,代码来源:cmds_events_doc.py

示例2: _gather_files

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def _gather_files(input_root, output_dir, skip_dirs, wiki_only):
    if not exists(output_dir):
        mkdir(output_dir)

    all_files = []
    for root, dirs, filenames in walk(input_root):
        if skip_dirs:
            output = join(output_dir, relpath(root, input_root))
            if exists(output):
                continue
        path = relpath(root, input_root)
        normalized_path = normalize_wiki_filename(path)
        if not exists(join(output_dir, normalized_path)):
            mkdir(join(output_dir, normalized_path))
        all_files += [join(path, x) for x in filenames]
    if wiki_only:
        all_files = [x for x in all_files if "wikipedia/" in x]
    return all_files 
开发者ID:thunlp,项目名称:XQA,代码行数:20,代码来源:evidence_corpus.py

示例3: relpath

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def relpath(path, start=os.path.curdir):
            """Return a relative version of a path"""
            from os.path import sep, curdir, join, abspath, commonprefix, \
                 pardir

            if not path:
                raise ValueError("no path specified")

            start_list = abspath(start).split(sep)
            path_list = abspath(path).split(sep)

            # Work out how much of the filepath is shared by start and path.
            i = len(commonprefix([start_list, path_list]))

            rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
            if not rel_list:
                return curdir
            return join(*rel_list) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:plot_directive.py

示例4: __call__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def  __call__(self, options=[], display=True):
        """
        Fill a LinePicker with a list of options. 
        
        When display=False it just fills the Line 
        Picker for later showing the options with LinePicker.display method.
        """
        # Make sure it is a list otherwise it may receive
        # an iterator and display no results even when there are
        # errors.
        options = list(options)
        ranges = zip(('%s - %s:%s' % (msg, relpath(filename), line)
        for filename, line, msg in options), options)

        ranges = list(ranges)
        super(LinePicker, self).__call__(ranges, display) 
开发者ID:vyapp,项目名称:vy,代码行数:18,代码来源:widgets.py

示例5: run

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def run(model_path, model_name, tenant_id, service_principal_id,
        service_principal_password, subscription_id, resource_group, workspace, tags):
    auth_args = {
        'tenant_id': tenant_id,
        'service_principal_id': service_principal_id,
        'service_principal_password': service_principal_password
    }

    ws_args = {
        'auth': ServicePrincipalAuthentication(**auth_args),
        'subscription_id': subscription_id,
        'resource_group': resource_group
    }

    ws = Workspace.get(workspace, **ws_args)

    print(ws.get_details())

    print('\nSaving model {} to {}'.format(model_path, model_name))

    # Model Path needs to be relative
    model_path = relpath(model_path, '.')

    model = Model.register(ws, model_name=model_name, model_path=model_path, tags=tags)
    print('Done!') 
开发者ID:aronchick,项目名称:kubeflow-and-mlops,代码行数:27,代码来源:register.py

示例6: get_name_texts_from_parent_folder

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def get_name_texts_from_parent_folder(gpath_list, img_dir, fmtkey=None):
    """
    Input: gpath_list
    Output: names based on the parent folder of each image
    """
    #from os.path import commonprefix
    relgpath_list = [relpath(gpath, img_dir) for gpath in gpath_list]
    #_prefix = commonprefix(gpath_list)
    #relgpath_list = [relpath(gpath, _prefix) for gpath in gpath_list]
    _name_list  = [dirname(relgpath) for relgpath in relgpath_list]

    if fmtkey is not None:
        #fmtkey = 'African Wild Dog: {name}'
        import parse
        parse_results = [parse.parse(fmtkey, name) for name in _name_list]
        _name_list = [res['name'] if res is not None else name
                      for name, res in zip(_name_list, parse_results)]

    name_list = list(map(normalize_name, _name_list))
    return name_list 
开发者ID:Erotemic,项目名称:ibeis,代码行数:22,代码来源:ingest_database.py

示例7: __directory_contents

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def __directory_contents(self, directory, recursive=True):
        contents = []
        if recursive:
            for path, _, files in walk(directory):
                relative_path = relpath(path, directory)
                for name in files:
                    # Return file1.txt, dataset_1_files/image.png, etc... don't
                    # include . in path.
                    if relative_path != curdir:
                        contents.append(join(relative_path, name))
                    else:
                        contents.append(name)
        else:
            if os.path.isdir(directory):
                for name in os.listdir(directory):
                    contents.append(name)
        return contents

    # Following abstractions store metadata related to jobs. 
开发者ID:galaxyproject,项目名称:pulsar,代码行数:21,代码来源:__init__.py

示例8: _generate_fontkey

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def _generate_fontkey(fonts, targets, data_dir):
    lines = ['<p style="margin-bottom:5px"><b>Targets</b>']
    lines.append('<div style="margin-left:20px"><table class="key">')
    for tid, target in enumerate(targets):
        lines.append('<tr><th><a href="#target_%s">%s</a>' % (tid, target.name))
    lines.append("</table></div>")

    lines.append('<p style="margin-bottom:5px"><b>Fonts</b>')
    lines.append('<div style="margin-left:20px"><table class="key">')
    for key, keyinfos in fonts:
        for font, name, _ in keyinfos:
            rel_font = path.relpath(font, data_dir) if font else "(no font)"
            lines.append("<tr><th>%s<td>%s<td>%s" % (key, name, rel_font))
    lines.append("</table></div>")

    return "\n".join(lines) 
开发者ID:googlefonts,项目名称:nototools,代码行数:18,代码来源:generate_dingbats_html.py

示例9: save_imglist

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def save_imglist(self, fname=None, root=None, shuffle=False):
        """
        save imglist to disk

        Parameters:
        ----------
        fname : str
            saved filename
        """
        def progress_bar(count, total, suffix=''):
            import sys
            bar_len = 24
            filled_len = int(round(bar_len * count / float(total)))

            percents = round(100.0 * count / float(total), 1)
            bar = '=' * filled_len + '-' * (bar_len - filled_len)
            sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
            sys.stdout.flush()

        str_list = []
        for index in range(self.num_images):
            progress_bar(index, self.num_images)
            label = self.label_from_index(index)
            if label.size < 1:
                continue
            path = self.image_path_from_index(index)
            if root:
                path = osp.relpath(path, root)
            str_list.append('\t'.join([str(index), str(2), str(label.shape[1])] \
              + ["{0:.4f}".format(x) for x in label.ravel()] + [path,]) + '\n')
        if str_list:
            if shuffle:
                import random
                random.shuffle(str_list)
            if not fname:
                fname = self.name + '.lst'
            with open(fname, 'w') as f:
                for line in str_list:
                    f.write(line)
        else:
            raise RuntimeError("No image in imdb") 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:43,代码来源:imdb.py

示例10: dir2zip

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def dir2zip(in_dir, zip_fname):
    """ Make a zip file `zip_fname` with contents of directory `in_dir`

    The recorded filenames are relative to `in_dir`, so doing a standard zip
    unpack of the resulting `zip_fname` in an empty directory will result in
    the original directory contents.

    Parameters
    ----------
    in_dir : str
        Directory path containing files to go in the zip archive
    zip_fname : str
        Filename of zip archive to write
    """
    z = zipfile.ZipFile(zip_fname, 'w',
                        compression=zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(in_dir):
        for file in files:
            in_fname = pjoin(root, file)
            in_stat = os.stat(in_fname)
            # Preserve file permissions, but allow copy
            info = zipfile.ZipInfo(in_fname)
            info.filename = relpath(in_fname, in_dir)
            if os.path.sep == '\\':
                # Make the path unix friendly on windows.
                # PyPI won't accept wheels with windows path separators
                info.filename = relpath(in_fname, in_dir).replace('\\', '/')
            # Set time from modification time
            info.date_time = time.localtime(in_stat.st_mtime)
            # See https://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip/48435482#48435482 # noqa: E501
            # Also set regular file permissions
            perms = stat.S_IMODE(in_stat.st_mode) | stat.S_IFREG
            info.external_attr = perms << 16
            with open_readable(in_fname, 'rb') as fobj:
                contents = fobj.read()
            z.writestr(info, contents, zipfile.ZIP_DEFLATED)
    z.close() 
开发者ID:matthew-brett,项目名称:delocate,代码行数:39,代码来源:tools.py

示例11: timid_relpath

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def timid_relpath(arg):
    """convert an argument to a relative path, carefully"""
    # TODO-TEST: unit tests
    from os.path import isabs, relpath, sep
    if isabs(arg):
        result = relpath(arg)
        if result.count(sep) + 1 < arg.count(sep):
            return result

    return arg 
开发者ID:edmundmok,项目名称:mealpy,代码行数:12,代码来源:venv_update.py

示例12: rp_calmjs

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def rp_calmjs(mapping):
    # helper to remap all path values in the provided mapping to
    # be relative of calmjs distribution location
    return {k: relpath(v, calmjs_dist_dir) for k, v in mapping.items()} 
开发者ID:calmjs,项目名称:calmjs,代码行数:6,代码来源:test_indexer.py

示例13: _get_img_element

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def _get_img_element(self, image_file, image_title):
        """Create an img html element

        :param image_file: filename of the image
        :param image_title: image title
        :returns: str with the img element
        """
        if not image_file:
            return ''
        image_file_path = path.relpath(image_file, self.output_directory).replace('\\', '/')
        return '<img src="{}" title="{}"/>'.format(image_file_path, image_title) 
开发者ID:Telefonica,项目名称:toolium,代码行数:13,代码来源:visual_test.py

示例14: check_path

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def check_path(options, rootdir=None, candidates=None, code=None):
    """Check path.

    :param rootdir: Root directory (for making relative file paths)
    :param options: Parsed pylama options (from pylama.config.parse_options)

    :returns: (list) Errors list

    """
    if not candidates:
        candidates = []
        for path_ in options.paths:
            path = op.abspath(path_)
            if op.isdir(path):
                for root, _, files in walk(path):
                    candidates += [op.relpath(op.join(root, f), CURDIR) for f in files]
            else:
                candidates.append(path)

    if rootdir is None:
        rootdir = path if op.isdir(path) else op.dirname(path)

    paths = []
    for path in candidates:

        if not options.force and not any(l.allow(path) for _, l in options.linters):
            continue

        if not op.exists(path):
            continue

        paths.append(path)

    if options.async:
        return check_async(paths, options, rootdir)

    errors = []
    for path in paths:
        errors += run(path=path, code=code, rootdir=rootdir, options=options)
    return errors 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:42,代码来源:main.py

示例15: check_file

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import relpath [as 别名]
def check_file(path):
    from pylama.main import parse_options, process_paths
    from pylama.config import CURDIR

    options = parse_options()
    path = op.relpath(str(path), CURDIR)
    return process_paths(options, candidates=[path], error=False)

# pylama:ignore=D,E1002,W0212,F0001 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:11,代码来源:pytest.py


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