當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。