Python os.path.relpath() Examples

The following are code examples for showing how to use os.path.relpath(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: moler   Author: nokia   File: cmds_events_doc.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 2
Project: XQA   Author: thunlp   File: evidence_corpus.py    MIT License 6 votes vote down vote up
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 
Example 3
Project: denite-extra   Author: neoclide   File: quickfix.py    MIT License 6 votes vote down vote up
def convert(self, val, index, context):
        root = context['__root']
        bufnr = val['bufnr']
        line = int(val['lnum']) if bufnr != 0 else 0
        col = int(val['col']) if bufnr != 0 else 0
        location = '' if line == 0 and col == 0 else '%d col %d' % (line, col)
        if val['type']:
            location = location + ' ' + get_type(val['type'])

        fname = "" if bufnr == 0 else self.vim.eval('bufname(' + str(bufnr) + ')')
        word = '{fname} |{location}| {text}'.format(
            fname=relpath(fname, root),
            location=location,
            text=val['text'].replace('\n', ' '))

        return {
            'word': word,
            'action__text': val['text'],
            'action__path': fname,
            'action__line': line,
            'action__col': col,
            'action__buffer_nr': bufnr,
            'action__index': index,
            } 
Example 4
Project: gtfsman   Author: geops   File: gtfsman.py    GNU General Public License v2.0 6 votes vote down vote up
def init(self, path):
        # make directory
        if not os.path.exists(path):
            os.makedirs(path)

        will_be_name = relpath(os.path.abspath(path), self.options['--base-folder'])

        url = self.options['<url>']

        if not url:
            # ask for zip URL
            url = raw_input('Enter feed URL for new feed "%s": ' % will_be_name)
        if self._download_feed(path, url):
            self._store_feed_url(url, path)
            self._clear_cache(path)
            f = self._get_feed_by_name(will_be_name)
            color = self._get_feed_color(f)
            print color + 'Initialized new feed in %s \033[0m' % path
        else:
            print color + 'Initialization of %s failed.\033[0m' % path 
Example 5
Project: gtfsman   Author: geops   File: gtfsman.py    GNU General Public License v2.0 6 votes vote down vote up
def _loadfeed(self, path):
        try:
            if not self._is_gtfs(path):
                raise Exception('Feed not found.')

            # read date validity
            feed = {}
            feed['name'] = relpath(os.path.abspath(path), self.options['--base-folder'])
            feed['data_from'] = datetime.strptime(self._parse_calendars(path)['from_date'], "%Y%m%d")
            feed['data_to'] = datetime.strptime(self._parse_calendars(path)['to_date'], "%Y%m%d")
            feed['url'] = self._parse_feed_url(path)
            feed['fullpath'] = path
            feed['has_shapes'] = os.path.isfile(os.path.join(path, 'shapes.txt'))
            feed['has_fare'] = os.path.isfile(os.path.join(path, 'fare_attributes.txt'))
            feed['postprocess'] = self._parse_postprocess_cmd(path)

            if self.options['--checkremotedate']:
                feed['has_newer_zip'], feed['remote_date'], feed['local_date'] = self._check_for_newer_zip(path, feed['url'])

            self._write_span_cache(feed)
            return feed
        except Exception as err:
            print 'Error while parsing ' + str(path)
            print err
            return None 
Example 6
Project: Computable   Author: ktraunmueller   File: plot_directive.py    MIT License 6 votes vote down vote up
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) 
Example 7
Project: kubeflow-and-mlops   Author: aronchick   File: register.py    Apache License 2.0 6 votes vote down vote up
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!') 
Example 8
Project: Biscuit   Author: Macquarie-MEG-Research   File: utils.py    MIT License 6 votes vote down vote up
def get_bidsobj_info(obj):
    """Return a string representation of a BIDS object from bidshandler."""
    if isinstance(obj, Project):
        return ' '.join(
            ['Project',
             'ID: {0}'.format(obj.ID)])
    elif isinstance(obj, Subject):
        return ' '.join(
            ['Subject',
             'ID: {0}'.format(obj.ID),
             '(in Project {0})'.format(obj.project.ID)])
    elif isinstance(obj, Session):
        return ' '.join(
            ['Session',
             'ID: {0}'.format(obj.ID),
             '(in {0}/{1})'.format(obj.project.ID, obj.subject.ID)])
    elif isinstance(obj, Scan):
        bt_path = obj.bids_tree.path
        return ' '.join(
            ['Scan',
             '@ {0}'.format(op.relpath(obj.raw_file, bt_path))]) 
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: imdb.py    Apache License 2.0 5 votes vote down vote up
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") 
Example 10
Project: mealpy   Author: edmundmok   File: venv_update.py    MIT License 5 votes vote down vote up
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 
Example 11
Project: calmjs   Author: calmjs   File: test_indexer.py    GNU General Public License v2.0 5 votes vote down vote up
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()} 
Example 12
Project: toolium   Author: Telefonica   File: visual_test.py    Apache License 2.0 5 votes vote down vote up
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) 
Example 13
Project: seamseg   Author: mapillary   File: dataset.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getitem__(self, item):
        # Load image
        with Image.open(self._images[item]["path"]) as img_raw:
            size = (img_raw.size[1], img_raw.size[0])
            img = self.transform(img_raw.convert(mode="RGB"))

        return {
            "img": img,
            "idx": self._images[item]["idx"],
            "size": size,
            "abs_path": self._images[item]["path"],
            "rel_path": path.relpath(self._images[item]["path"], self.in_dir),
        } 
Example 14
Project: snakemakelib-core   Author: percyfal   File: setup.py    MIT License 5 votes vote down vote up
def package_path(path, filters=()):
    if not os.path.exists(path):
        raise RuntimeError("packaging non-existent path: %s" % path)
    elif os.path.isfile(path):
        package_data.append(relpath(path, 'snakemakelib'))
    else:
        for path, dirs, files in os.walk(path):
            path = relpath(path, 'snakemakelib')
            for f in files:
                if not filters or f.endswith(filters):
                    package_data.append(join(path, f)) 
Example 15
Project: LibCloud   Author: stewnorriss   File: py3.py    Apache License 2.0 5 votes vote down vote up
def relpath(path, start=posixpath.curdir):   # NOQA
        """Return a relative version of a path"""
        if not path:
            raise ValueError("no path specified")
        start_list = posixpath.abspath(start).split(posixpath.sep)
        path_list = posixpath.abspath(path).split(posixpath.sep)
        # Work out how much of the filepath is shared by start and path.
        i = len(posixpath.commonprefix([start_list, path_list]))
        rel_list = [posixpath.pardir] * (len(start_list) - i) + path_list[i:]
        if not rel_list:
            return posixpath.curdir
        return posixpath.join(*rel_list) 
Example 16
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def getCollapsedGroups(fileName):
    """Provides None if not found"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            return project.getFileGroups(key)
    return Settings().getFileGroups(fileName) 
Example 17
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def setCollapsedGroups(fileName, groups):
    """Sets the file collapsed groups"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            project.setFileGroups(key, groups)
            return
    Settings().setFileGroups(fileName, groups) 
Example 18
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def addCollapsedGroup(fileName, group):
    """Adds a group into a list collapsed group for a file"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            project.addFileGroup(key, group)
            return
    Settings().addFileGroup(fileName, group) 
Example 19
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def removeCollapsedGroup(fileName, group):
    """Removes a group from a list of collapsed groups for a file"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            project.removeFileGroup(key, group)
            return
    Settings().removeFileGroup(fileName, group) 
Example 20
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def getFileEncoding(fileName):
    """Provides None if not found"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            return project.getFileEncoding(key)
    return Settings().getFileEncoding(fileName) 
Example 21
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def getRunParameters(fileName):
    """Provides the run parameters"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            return project.getRunParameters(key)
    return Settings().getRunParameters(fileName) 
Example 22
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def addRunParams(fileName, params):
    """Registers new latest run parameters"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            project.addRunParameters(key, params)
            return
    Settings().addRunParameters(fileName, params) 
Example 23
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def getFilePosition(fileName):
    """Provides the position or (-1,-1,-1,-1,-1) if not found"""
    project = GlobalData().project
    if project.isLoaded():
        if project.isProjectFile(fileName):
            key = relpath(fileName, dirname(project.fileName))
            return project.getFilePosition(key)
    return Settings().getFilePosition(fileName) 
Example 24
Project: codimension   Author: SergeySatskiy   File: diskvaluesrelay.py    GNU General Public License v3.0 5 votes vote down vote up
def updateFilePosition(fileName, line, pos, firstLine,
                       horizontalPos, verticalPos):
    """Updates the position for the file"""
    if fileName:
        project = GlobalData().project
        if project.isLoaded():
            if project.isProjectFile(fileName):
                key = relpath(fileName, dirname(project.fileName))
                project.updateFilePosition(key, line, pos, firstLine,
                                           horizontalPos, verticalPos)
                return
        Settings().updateFilePosition(fileName, line, pos, firstLine,
                                      horizontalPos, verticalPos) 
Example 25
Project: codimension   Author: SergeySatskiy   File: projectproperties.py    GNU General Public License v3.0 5 votes vote down vote up
def onAddImportDir(self):
        """Displays a directory selection dialog"""
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog | QFileDialog.ShowDirsOnly
        dirName = QFileDialog.getExistingDirectory(
            self, 'Select import directory', self.dirEdit.text(),
            options=options)

        if not dirName:
            return

        # There are 2 cases: new project or
        # editing the existed project properties
        if self.__project is None:
            # It a new project; the project path could be editedd
            dirToInsert = dirName
        else:
            # This is an existed project; no way the project path is changed
            # Let's decide it a relative path should be used here
            if self.__project.isProjectDir(dirName):
                dirToInsert = relpath(dirName, self.dirEdit.text())
            else:
                dirToInsert = dirName

        index = 0
        while index < self.importDirList.count():
            if self.importDirList.item(index).text() == dirToInsert:
                logging.warning("The directory '%s' is already in the list of "
                                "imported directories and is not added.",
                                dirName)
                return
            index += 1

        self.importDirList.addItem(dirToInsert)
        self.importDirList.setCurrentRow(self.importDirList.count() - 1) 
Example 26
Project: plex-linker-beta   Author: jd4883   File: movie.py    GNU General Public License v3.0 5 votes vote down vote up
def get_relative_movies_path(self):
	return relpath(self.absolute_movies_path, str(environ['DOCKER_MEDIA_PATH'])) 
Example 27
Project: TESTGIT   Author: B-ROY   File: loader.py    Apache License 2.0 5 votes vote down vote up
def _get_name_from_path(self, path):
        path = os.path.splitext(os.path.normpath(path))[0]

        _relpath = relpath(path, self._top_level_dir)
        assert not os.path.isabs(_relpath), "Path must be within the project"
        assert not _relpath.startswith('..'), "Path must be within the project"

        name = _relpath.replace(os.path.sep, '.')
        return name 
Example 28
Project: XQA   Author: thunlp   File: evidence_corpus.py    MIT License 5 votes vote down vote up
def list_documents(self):
        if self.file_id_map is not None:
            return list(self.file_id_map.keys())
        f = []
        for dirpath, dirnames, filenames in walk(self.directory):
            if dirpath == self.directory:
                # Exclude files in the top level dir, like the vocab file
                continue
            if self.directory != dirpath:
                rel_path = relpath(dirpath, self.directory)
                f += [join(rel_path, x[:-4]) for x in filenames]
            else:
                f += [x[:-4] for x in filenames]
        return f 
Example 29
Project: aactivator   Author: Yelp   File: aactivator.py    MIT License 5 votes vote down vote up
def path_is_under(path, under):
    relpath = os.path.relpath(path, under).split('/')
    return not relpath[:1] == ['..'] 
Example 30
Project: aactivator   Author: Yelp   File: aactivator.py    MIT License 5 votes vote down vote up
def security_check(path):
    if not os.path.exists(path):
        return 'aactivator: File does not exist: ' + path
    insecure_path = insecure(path)
    if insecure_path is not None:
        return (
            'aactivator: Cowardly refusing to source {0} because writeable by others: {1}'
            .format(relpath(path), relpath(insecure_path))
        ) 
Example 31
Project: ACE   Author: IntegralDefense   File: cuckoo.py    Apache License 2.0 5 votes vote down vote up
def download_dropped(self, server, id, analysis, path):
        logging.debug("downloading dropped files")
        r = requests.get("{}://{}/api/tasks/get/dropped/{}/".format(self.protocol, server, id), 
                         proxies=self.proxies, verify=False) # XXX
        if r.status_code != 200:
            logging.warning("failed to get dropped files: status code {}".format(r.status_code))
            return
        try:
            if r.content[0] == 123:
                response = json.loads(r.text)
                if response['error'] == True:
                    logging.warning("failed to get dropped files: {}".format(response['error_value']))
                    return
        except Exception:
            pass

        # extract all dropped files
        cuckoo_dir = "{}.cuckoo".format(path)
        if not isdir(cuckoo_dir):
            mkdir(cuckoo_dir)
        with tarfile.open(fileobj=io.BytesIO(r.content)) as tar_archive:
            members = tar_archive.getmembers()
            for member in members:
                logging.debug("member name = {}".format(member.name))
                if '.' not in member.name:
                    tar_archive.extract(member, path=cuckoo_dir)
                    dropped_file = join(cuckoo_dir, member.name)
                    magic_sig = open(dropped_file, 'rb').read(2)
                    logging.debug("magic_sig = {}".format(magic_sig))
                    if magic_sig == b"MZ":
                        new_path = "{}.exe".format(dropped_file)
                        logging.debug("renaming {} to {}".format(dropped_file, new_path))
                        rename(dropped_file, new_path)
                        analysis.add_observable(F_FILE, relpath(new_path, start=self.root.storage_dir))
                    else:
                        remove(dropped_file) 
Example 32
Project: SuRVoS2   Author: DiamondLightSource   File: utils.py    MIT License 5 votes vote down vote up
def check_relpath(path1, path2, exception=True):
    """
    Checks that the real path of `path2` is inside `path1`.

    Parameters
    ----------
    path1: str
        Path-like string. It can be relative or absolute.
    path2: str
        Path-like string. It can be relative or absolute.
    exception: bool (optional)
        Whether to return `False` or raise an exception in case
        `path2` is not relative to `path1`.

    Returns
    -------
    flag : str or bool
        Returns the full path from `path1` to `path2` or False
        if `path2` is not relative to `path1` (if `exception=False`).
    """
    p1 = op.normpath(path1)
    p2 = op.normpath(op.join(path1, path2))
    if op.relpath(p1, p2).endswith(op.basename(p1)):
        if exception:
            raise ValueError('Invalid path \'%s\'' % path2)
        return False
    return p2 
Example 33
Project: pycosio   Author: Accelize   File: functions_os_path.py    Apache License 2.0 5 votes vote down vote up
def relpath(path, start=None):
    """
    Return a relative file path to path either from the
    current directory or from an optional start directory.

    For storage objects, "path" and "start" are relative to
    storage root.

    "/" are not stripped on storage objects path. The ending slash is required
    on some storage to signify that target is a directory.

    Equivalent to "os.path.relpath".

    Args:
        path (path-like object): Path or URL.
        start (path-like object): Relative from this optional directory.
            Default to "os.curdir" for local files.

    Returns:
        str: Relative path.
    """
    relative = get_instance(path).relpath(path)
    if start:
        # Storage relative path
        # Replaces "\" by "/" for Windows.
        return os_path_relpath(relative, start=start).replace('\\', '/')
    return relative 
Example 34
Project: snakemake-rules   Author: percyfal   File: setup.py    MIT License 5 votes vote down vote up
def package_path(path, filters=()):
    if not os.path.exists(path):
        raise RuntimeError("packaging non-existent path: %s" % path)
    elif os.path.isfile(path):
        package_data.append(relpath(path, 'snakemake_rules'))
    else:
        for path, dirs, files in os.walk(path):
            path = relpath(path, 'snakemake_rules')
            for f in files:
                if not filters or f.endswith(filters):
                    package_data.append(join(path, f)) 
Example 35
Project: hyperhelpcore   Author: STealthy-and-haSTy   File: bootstrapper.py    MIT License 5 votes vote down vote up
def create_bootstrap_package(self, package, res_path):
        """
        Perform the task of actually creating the system bootstrap package from
        files in the given resource folder into the provided package.
        """
        try:
            success = True
            boot_file = "{file}.py".format(file=bootloader)

            with ZipFile(package, 'w') as zFile:
                for (path, dirs, files) in os.walk(res_path):
                    rPath = relpath(path, res_path) if path != res_path else ""

                    for file in files:
                        real_file = join(res_path, path, file)
                        archive_file = join(rPath, file)

                        if archive_file.endswith(".sublime-ignored"):
                            archive_file = archive_file[:-len(".sublime-ignored")]

                        if archive_file == boot_file:
                            content = self.create_boot_loader(real_file)
                            zFile.writestr(archive_file, content)
                        else:
                            zFile.write(real_file, archive_file)

        except Exception as err:
            success = False
            log("Bootstrap error: {reason}", reason=str(err))
            if os.path.exists(package):
                os.remove(package)

        return success 
Example 36
Project: pyreload   Author: pyreload   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def relpath(path, start=curdir):
        """Return a relative version of a path"""
        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) 
Example 37
Project: pyreload   Author: pyreload   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def path_make_relative(path):
    p = relpath(path)
    if os.path.isfile(p):
        return p
    elif p[-1] == os.path.sep:
        return p
    else:
        return p + os.path.sep 
Example 38
Project: Computable   Author: ktraunmueller   File: plot_directive.py    MIT License 5 votes vote down vote up
def relpath(path, start=os.path.curdir):
            """Return a relative version of a path"""
            from os.path import sep, curdir, join, abspath, commonprefix, \
                 pardir, splitunc

            if not path:
                raise ValueError("no path specified")
            start_list = abspath(start).split(sep)
            path_list = abspath(path).split(sep)
            if start_list[0].lower() != path_list[0].lower():
                unc_path, rest = splitunc(path)
                unc_start, rest = splitunc(start)
                if bool(unc_path) ^ bool(unc_start):
                    raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
                                                                        % (path, start))
                else:
                    raise ValueError("path is on drive %s, start on drive %s"
                                                        % (path_list[0], start_list[0]))
            # Work out how much of the filepath is shared by start and path.
            for i in range(min(len(start_list), len(path_list))):
                if start_list[i].lower() != path_list[i].lower():
                    break
            else:
                i += 1

            rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
            if not rel_list:
                return curdir
            return join(*rel_list) 
Example 39
Project: pipeline   Author: liorbenhorin   File: plat_other.py    MIT License 5 votes vote down vote up
def info_for(src, topdir):
    # ...it MUST not include a ".."" directory, and for files not "under" that
    # directory, absolute pathnames must be used. [2]
    if topdir is None or not is_parent(topdir, src):
        src = op.abspath(src)
    else:
        src = op.relpath(src, topdir)

    info  = "[Trash Info]\n"
    info += "Path=" + quote(src) + "\n"
    info += "DeletionDate=" + format_date(datetime.now()) + "\n"
    return info 
Example 40
Project: bhmm   Author: bhmm   File: setup.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_package_data(data_root, package_root):
    files = []
    for root, dirnames, filenames in os.walk(data_root):
        for fn in filenames:
            files.append(relpath(join(root, fn), package_root))
    return files


################################################################################
# SETUP
################################################################################ 
Example 41
Project: tg_userbot   Author: watzon   File: __init__.py    MIT License 5 votes vote down vote up
def __list_all_modules():
    from os.path import dirname, isfile, relpath
    from glob import glob

    root_dir = dirname(__file__)
    mod_paths = glob(root_dir + "/**/*.py", recursive=True)
    all_modules = [
        '.'.join(relpath(f, root_dir).split('/'))[:-3]
        for f in mod_paths
        if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py")
    ]
    return all_modules 
Example 42
Project: ACS-VRP   Author: AuxinJeron   File: TsplibParser.py    Apache License 2.0 5 votes vote down vote up
def read_file(self, file_path):
        self.file_path = path.relpath(file_path)
        file = open(file_path, 'r')
        self.scan_keywords(file)
        self.cities_coord = self.cities_coord[1:] 
Example 43
Project: mnd   Author: stuaxo   File: setup.py    MIT License 5 votes vote down vote up
def run(self):
        global here

        for path_spec in self.CLEAN_FILES:
            # Make paths absolute and relative to this path
            abs_paths = glob(normpath(join(here, path_spec)))
            for path in [str(p) for p in abs_paths]:
                if not path.startswith(here):
                    # Die if path in CLEAN_FILES is absolute + outside this directory
                    raise ValueError("%s is not a path inside %s" % (path, here))
                print('removing %s' % relpath(path))
                rmtree(path) 
Example 44
Project: fbs   Author: mherrmann   File: _aws.py    GNU General Public License v3.0 5 votes vote down vote up
def upload_folder_contents(dir_path, dest_path, bucket, key, secret):
    result = []
    for file_path in _iter_files_recursive(dir_path):
        file_relpath = relpath(file_path, dir_path)
        # Replace backslashes on Windows by forward slashes:
        file_relpath = file_relpath.replace(os.sep, '/')
        file_dest = dest_path + '/' + file_relpath
        upload_file(file_path, file_dest, bucket, key, secret)
        result.append(file_dest)
    return result 
Example 45
Project: fbs   Author: mherrmann   File: resources.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_files_to_copy(src_dir_or_file, dest_dir, exclude):
    excludes = _paths(map(path, exclude))
    if isfile(src_dir_or_file) and src_dir_or_file not in excludes:
        yield src_dir_or_file, join(dest_dir, basename(src_dir_or_file))
    else:
        for (subdir, _, files) in os.walk(src_dir_or_file):
            dest_subdir = join(dest_dir, relpath(subdir, src_dir_or_file))
            for file_ in files:
                file_path = join(subdir, file_)
                dest_path = join(dest_subdir, file_)
                if file_path not in excludes:
                    yield file_path, dest_path 
Example 46
Project: fbs   Author: mherrmann   File: setup.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_package_data(pkg_dir, data_subdir):
    result = []
    for dirpath, _, filenames in os.walk(join(pkg_dir, data_subdir)):
        for filename in filenames:
            filepath = join(dirpath, filename)
            result.append(relpath(filepath, pkg_dir))
    return result 
Example 47
Project: airflow   Author: apache   File: exampleinclude.py    Apache License 2.0 5 votes vote down vote up
def doctree_read(app, doctree):
    """
    Reads documentation tree for the application and register sources in the generated documentation.

    :param app: application
    :param doctree: documentation tree

    :return None

    """
    env = app.builder.env
    if not hasattr(env, "_viewcode_modules"):
        env._viewcode_modules = {}  # type: ignore

    if app.builder.name == "singlehtml":
        return

    for objnode in doctree.traverse(ExampleHeader):
        filepath = objnode.get("filename")
        relative_path = path.relpath(
            filepath, path.commonprefix([app.config.exampleinclude_sourceroot, filepath])
        )
        modname = relative_path.replace("/", ".")[:-3]
        show_button = register_source(app, env, modname)
        onlynode = create_node(env, relative_path, show_button)

        objnode.replace_self(onlynode)
# pylint: enable=protected-access 
Example 48
Project: AnyBlok   Author: AnyBlok   File: plugins.py    Mozilla Public License 2.0 5 votes vote down vote up
def isindir(path, dirpath):
    # normpath simplifies stuff like a/../c but doesn't follow symlinks
    # that's what we need. Nose will feed us absolute paths, btw
    return not relpath(normpath(path), normpath(dirpath)).startswith(pardir) 
Example 49
Project: GrowthNodes   Author: hsab   File: setup.py    GNU General Public License v3.0 5 votes vote down vote up
def iterRelativeAddonFiles(directory):
    if not os.path.isdir(directory):
        return

    for root, folders, files in os.walk(directory, topdown = True):
        for folder in folders:
            if ignoreAddonDirectory(folder):
                folders.remove(folder)

        for fileName in files:
            if not ignoreAddonFile(fileName):
                yield relpath(join(root, fileName), directory) 
Example 50
Project: darts-UNIQ   Author: yochaiz   File: utils.py    Apache License 2.0 5 votes vote down vote up
def create_exp_dir(resultFolderPath):
    # create folders
    if not os.path.exists(resultFolderPath):
        os.makedirs(resultFolderPath)

    codeFilename = 'code.zip'
    zipPath = '{}/{}'.format(resultFolderPath, codeFilename)
    zipf = ZipFile(zipPath, 'w', ZIP_DEFLATED)

    # init project base folder
    baseFolder = path.dirname(path.abspath(getfile(currentframe())))  # script directory
    baseFolder += '/..'
    # init path function
    pathFunc = lambda fn: path.relpath(fn, baseFolder)
    # init folders we want to zip
    foldersToZip = ['cnn/models', 'cnn/trainRegime', 'cnn/gradEstimators', 'cnn/managers', 'UNIQ', 'NICE']
    # save folders files
    for folder in foldersToZip:
        zipFolder('{}/{}'.format(baseFolder, folder), pathFunc, zipf)

    # save cnn folder files
    foldersToZip = ['cnn']
    for folder in foldersToZip:
        folderName = '{}/{}'.format(baseFolder, folder)
        for file in listdir(folderName):
            filePath = '{}/{}'.format(folderName, file)
            if path.isfile(filePath):
                zipf.write(filePath, pathFunc(filePath))

    # close zip file
    zipf.close()

    return zipPath, codeFilename