Python os.path.isabs() Examples

The following are 30 code examples of os.path.isabs(). 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 os.path , or try the search function .
Example #1
Source File: test_base_server.py    From hdl_checker with GNU General Public License v3.0 6 votes vote down vote up
def test():
            filename = p.relpath(
                p.join(TEST_PROJECT, "another_library", "foo.vhd"),
                str(it.project.root_dir),
            )

            it.assertFalse(p.isabs(filename))

            diagnostics = it.project.getMessagesByPath(Path(filename))

            it.assertIn(
                ObjectIsNeverUsed(
                    filename=Path(p.join(TEST_PROJECT, "another_library", "foo.vhd")),
                    line_number=28,
                    column_number=11,
                    object_type="signal",
                    object_name="neat_signal",
                ),
                diagnostics,
            ) 
Example #2
Source File: plat_win.py    From pipeline with MIT License 6 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + '\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        msg = "Couldn't perform operation. Error code: %d" % result
        raise OSError(msg) 
Example #3
Source File: setup.py    From collectd-cloudwatch with MIT License 6 votes vote down vote up
def _get_credentials_path(self):
        recommended_path = path.expanduser('~') + '/.aws/credentials'
        creds_path = ""
        if not self.non_interactive:
            while not path.isabs(creds_path):
                creds_path = Prompt(
                    message="Enter absolute path to AWS credentials file [" + Color.green(recommended_path) + "]: ",
                    default=recommended_path).run()
        else:
            if self.creds_path:
                if path.isabs(self.creds_path):
                    creds_path = self.creds_path
            else:
                creds_path = recommended_path
        make_dirs(path.dirname(creds_path))
        return creds_path 
Example #4
Source File: pytest.py    From clonedigger with GNU General Public License v3.0 6 votes vote down vote up
def remove_local_modules_from_sys(testdir):
    """remove all modules from cache that come from `testdir`

    This is used to avoid strange side-effects when using the
    testall() mode of pytest.
    For instance, if we run pytest on this tree::
    
      A/test/test_utils.py
      B/test/test_utils.py

    we **have** to clean sys.modules to make sure the correct test_utils
    module is ran in B
    """
    for modname, mod in list(sys.modules.items()):
        if mod is None:
            continue
        if not hasattr(mod, '__file__'):
            # this is the case of some built-in modules like sys, imp, marshal
            continue
        modfile = mod.__file__
        # if modfile is not an asbolute path, it was probably loaded locally
        # during the tests
        if not osp.isabs(modfile) or modfile.startswith(testdir):
            del sys.modules[modname] 
Example #5
Source File: file.py    From EasyClangComplete with MIT License 6 votes vote down vote up
def canonical_path(input_path, folder=''):
        """Return a canonical path of the file.

        Args:
            input_path (str): path to convert.
            folder (str, optional): parent folder.

        Returns:
            str: canonical path
        """
        if not input_path:
            return None
        input_path = path.expanduser(input_path)
        if not path.isabs(input_path):
            input_path = path.join(folder, input_path)
        normpath = path.normpath(input_path)
        if path.exists(normpath):
            return path.realpath(normpath)
        return normpath 
Example #6
Source File: dired.py    From dired with MIT License 6 votes vote down vote up
def _move(self, path):
        if path == self.path:
            return

        files = self.get_marked() or self.get_selected()

        if not isabs(path):
            path = join(self.path, path)
        if not isdir(path):
            sublime.error_message('Not a valid directory: {}'.format(path))
            return

        # Move all items into the target directory.  If the target directory was also selected,
        # ignore it.
        files = self.get_marked() or self.get_selected()
        path = normpath(path)
        for filename in files:
            fqn = normpath(join(self.path, filename))
            if fqn != path:
                shutil.move(fqn, path)
        self.view.run_command('dired_refresh') 
Example #7
Source File: cmake_file.py    From EasyClangComplete with MIT License 6 votes vote down vote up
def __get_cmake_deps(deps_file):
        """Parse dependencies from Makefile.cmake.

        Args:
            deps_file (str): Full path to Makefile.cmake file.

        Returns:
            str[]: List of full paths to dependency files.
        """
        folder = path.dirname(path.dirname(deps_file))
        deps = []
        with open(deps_file, 'r') as f:
            content = f.read()
            found = CMakeFile._DEP_REGEX.findall(content)
            for dep in found:
                if not path.isabs(dep):
                    dep = path.join(folder, dep)
                deps.append(dep)
        return deps 
Example #8
Source File: localfile.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def __sanitize(self, pathname):
        """
        Makes sure the given pathname lies within the plugin folder.
        Also makes it an absolute pathname.

        .. warning: Internally used by GoLismero, do not call!
        """

        # Absolute pathnames are not allowed.
        if path.isabs(pathname):
            msg = "Absolute pathnames are not allowed: %r"
            raise ValueError(msg % pathname)

        # Turn the pathname into a local pathname within the plugin folder.
        pathname = path.join(self.plugin_path, pathname)
        pathname = path.abspath(pathname)
        if not pathname.startswith(self.plugin_path):
            msg = "Pathname may not be outside the plugin folder: %r"
            raise ValueError(msg % self.plugin_path)

        # Return the sanitized pathname.
        return pathname


    #-------------------------------------------------------------------------- 
Example #9
Source File: stats.py    From DSAlign with Mozilla Public License 2.0 6 votes vote down vote up
def load_catalog(self, catalog_path, ignore_missing=True):
        catalog = path.abspath(catalog_path)
        catalog_dir = path.dirname(catalog)
        with open(catalog, 'r') as catalog_file:
            catalog_entries = json.load(catalog_file)
        for entry in AlignmentStatistics.progress(catalog_entries, desc='Reading catalog'):
            aligned_path = entry['aligned']
            if not path.isabs(aligned_path):
                aligned_path = path.join(catalog_dir, aligned_path)
            if path.isfile(aligned_path):
                self.load_aligned(aligned_path)
            else:
                if ignore_missing:
                    continue
                else:
                    fail('Problem loading catalog "{}": Missing referenced alignment file "{}"'
                         .format(catalog_path, aligned_path)) 
Example #10
Source File: sandbox.py    From incubator-retired-cotton with Apache License 2.0 6 votes vote down vote up
def __init__(self, root):
    """
      Initializes the sandbox.

      :param root: Root path of the sandbox.

      The sandbox makes sure that the folder paths it exposes as properties are created.
    """
    if not isabs(root):
      raise ValueError("Only an absolute path is allowed for 'root")

    self._root = root

    safe_mkdir(self.bin)
    safe_mkdir(self.lib)
    safe_mkdir(self.var)
    safe_mkdir(self.mysql_var)
    safe_mkdir(self.mysql_data_dir)
    safe_mkdir(self.mysql_tmp_dir)
    safe_mkdir(self.mysql_log_dir) 
Example #11
Source File: config_parser.py    From hdl_checker with GNU General Public License v3.0 5 votes vote down vote up
def _getSourcePaths(self, path):  # type: (str) -> Iterable[str]
        """
        Normalizes and handles absolute/relative paths
        """
        source_path = p.normpath(p.expanduser(path))
        # If the path to the source file was not absolute, we assume
        # it was relative to the config file base path
        if not p.isabs(source_path):
            fname_base_dir = p.dirname(self.filename.abspath)
            source_path = p.join(fname_base_dir, source_path)

        return glob(source_path) or [source_path] 
Example #12
Source File: test_common.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def test_get_filepath_or_buffer_with_path(self):
        filename = '~/sometest'
        filepath_or_buffer, _, _ = common.get_filepath_or_buffer(filename)
        assert filepath_or_buffer != filename
        assert isabs(filepath_or_buffer)
        assert os.path.expanduser(filename) == filepath_or_buffer 
Example #13
Source File: export.py    From DSAlign with Mozilla Public License 2.0 5 votes vote down vote up
def make_absolute(base_path, spec_path):
    if not path.isabs(spec_path):
        spec_path = path.join(base_path, spec_path)
    spec_path = path.abspath(spec_path)
    return spec_path if path.isfile(spec_path) else None 
Example #14
Source File: settings_storage.py    From EasyClangComplete with MIT License 5 votes vote down vote up
def __populate_flags_source_paths(self):
        """Populate variables inside flags sources."""
        def expand_paths_in_flags_if_needed(flags):
            """Expand paths in flags if they are present."""
            from os import path
            new_flags = []
            for flag in flags:
                if '=' not in flag:
                    new_flags.append(flag)
                split_flag = flag.split('=')
                prefix = split_flag[0].strip()
                value = split_flag[1].strip()
                expanded_values = self.__replace_wildcard_if_needed(
                    value)
                if not expanded_values:
                    continue
                joined_values = ';'.join(expanded_values)
                if path.isabs(expanded_values[0]):
                    new_flags.append(
                        prefix + '="' + joined_values + '"')
                else:
                    new_flags.append(prefix + '=' + joined_values)
            return new_flags

        if not self.flags_sources:
            log.critical(" Cannot update paths of flag sources.")
            return
        for idx, source_dict in enumerate(self.flags_sources):
            for option in SettingsStorage.FLAG_SOURCES_ENTRIES_WITH_PATHS:
                if option not in source_dict:
                    continue
                if not source_dict[option]:
                    continue
                if option == SettingsStorage.FLAGS_TAG:
                    source_dict[option] = expand_paths_in_flags_if_needed(
                        source_dict[option])
                else:
                    source_dict[option] = self.__replace_wildcard_if_needed(
                        source_dict[option]) 
Example #15
Source File: main.py    From hover-preview with MIT License 5 votes vote down vote up
def get_file(view: sublime.View, string: str, name: str) -> 'Tuple[str, Optional[str]]':
    """
    Try to get a file from the given `string` and test whether it's in the
    project directory.
    """

    # if it's an absolute path get it
    if osp.isabs(string):
        return string, None

    # if search_mode: "project", search only in project
    elif Settings.search_mode == "project":
        # Get base project folders
        base_folders = sublime.active_window().folders()
        # if "recursive": true, recursively search for the name
        if Settings.recursive:
            ch_rec = check_recursive(base_folders, name)
            if ch_rec:
                base_folder, root = ch_rec
                return osp.join(root, name), base_folder
            return "", None
        else:
            # search only in base folders for the relative path
            for base_folder in base_folders:
                file_name = osp.normpath(osp.join(base_folder, string))
                if osp.exists(file_name):
                    return file_name, base_folder
            return "", None
    # if search_mode: "file" join the relative path to the file path
    else:
        return osp.normpath(osp.join(osp.dirname(view.file_name()), string)), None 
Example #16
Source File: documenter.py    From schedula with European Union Public License 1.1 5 votes vote down vote up
def _plot(lines, dsp, dot_view_opt, documenter, dsp_opt):
    code_content = _import_docstring_code_content(documenter)
    hashkey = str(sorted(dot_view_opt.items())) + '\n'
    if code_content:
        hashkey += code_content[0]
    else:
        modname, objpath = documenter.modname, documenter.objpath
        if modname:
            hashkey += 'import %s\n' % modname
        if objpath:
            hashkey += 'from %s import %s\n' % (modname, '.'.join(objpath))

    fname = 'dispatcher-%s' % hashlib.sha1(hashkey.encode('utf-8')).hexdigest()
    env = documenter.env
    if osp.isabs(env.config.dispatchers_out_dir):
        dspdir = env.config.dispatchers_out_dir
    else:
        dspdir = osp.join(env.srcdir, env.config.dispatchers_out_dir)
    dspdir = osp.join(dspdir, fname)
    index = dot_view_opt.get('index', False)
    if osp.isdir(dspdir):
        fpath = glob.glob(osp.join(dspdir, '*.gv'))[0]
    else:
        smap = dsp.plot(**dot_view_opt)
        folder = next(iter(smap))
        fpath = osp.join(dspdir, '%s.gv' % folder.sitemap.foldername)
        dot = folder.dot(smap.rules(index=index))
        smap.render(directory=dspdir, index=index)
        dot.save(fpath, '')

    dsource = osp.dirname(osp.join(env.srcdir, env.docname))
    p = osp.relpath(fpath, dsource).replace('\\', '/')
    dsp_opt = dsp_opt.copy()
    dsp_opt['graphviz_dot'] = dot_view_opt.get('engine', 'dot')
    if index:
        dsp_opt['index'] = ''

    lines.append('.. dsp:: %s' % p)
    lines.extend('   :{}: {}'.format(k, v) for k, v in dsp_opt.items())
    lines.append('') 
Example #17
Source File: providers.py    From textX with MIT License 5 votes vote down vote up
def _load_referenced_models(self, model, encoding):
        for filename_pattern in self.filename_pattern_list:
            if not isabs(filename_pattern) and \
                    'project_root' in model._tx_model_params:
                filename_pattern = join(
                    model._tx_model_params['project_root'], filename_pattern)
            model._tx_model_repository.load_models_using_filepattern(
                filename_pattern, model=model, glob_args=self.glob_args,
                encoding=encoding, model_params=model._tx_model_params)
        for m in self.models_to_be_added_directly:
            model._tx_model_repository._add_model(m) 
Example #18
Source File: test_resources.py    From pyecore with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_uri_normalize_fileuri_abs():
    uri = URI('file:///test.xmi')
    assert path.isabs(uri.normalize()) 
Example #19
Source File: workspace.py    From core with Apache License 2.0 5 votes vote down vote up
def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, ignore, check_file_exists, force, fname):
    """
    Add a file or http(s) URL FNAME to METS in a workspace.
    If FNAME is not an http(s) URL and is not a workspace-local existing file, try to copy to workspace.
    """
    workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)

    kwargs = {'fileGrp': file_grp, 'ID': file_id, 'mimetype': mimetype, 'pageId': page_id, 'force': force, 'ignore': ignore}
    log = getLogger('ocrd.cli.workspace.add')
    log.debug("Adding '%s' (%s)", fname, kwargs)
    if not (fname.startswith('http://') or fname.startswith('https://')):
        if not fname.startswith(ctx.directory):
            if not isabs(fname) and exists(join(ctx.directory, fname)):
                fname = join(ctx.directory, fname)
            else:
                log.debug("File '%s' is not in workspace, copying", fname)
                try:
                    fname = ctx.resolver.download_to_directory(ctx.directory, fname, subdir=file_grp)
                except FileNotFoundError:
                    if check_file_exists:
                        log.error("File '%s' does not exist, halt execution!" % fname)
                        sys.exit(1)
        if check_file_exists and not exists(fname):
            log.error("File '%s' does not exist, halt execution!" % fname)
            sys.exit(1)
        if fname.startswith(ctx.directory):
            fname = relpath(fname, ctx.directory)
        kwargs['local_filename'] = fname

    kwargs['url'] = fname
    workspace.mets.add_file(**kwargs)
    workspace.save_mets()

# ----------------------------------------------------------------------
# ocrd workspace add-bulk
# ----------------------------------------------------------------------

# pylint: disable=bad-whitespace, broad-except 
Example #20
Source File: RVMatTools.py    From ArmAToolbox with GNU General Public License v3.0 5 votes vote down vote up
def mt_stripAddonPath(apath):
    if apath == "" or apath == None: 
        return ""
    if path.isabs(apath):
        p = path.splitdrive(apath)
        return p[1][1:]
    elif apath[0] == '\\':
        return apath[1:]
    else:
        return apath 
Example #21
Source File: _os.py    From python2017 with MIT License 5 votes vote down vote up
def abspathu(path):
        """
        Version of os.path.abspath that uses the unicode representation
        of the current working directory, thus avoiding a UnicodeDecodeError
        in join when the cwd has non-ASCII characters.
        """
        if not isabs(path):
            path = join(os.getcwdu(), path)
        return normpath(path) 
Example #22
Source File: plat_win.py    From FileManager with MIT License 5 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    path = get_short_path_name(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(path, len(path)+2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(None, None, path, result) 
Example #23
Source File: local_workflow_decorator.py    From cloudify-plugins-common with Apache License 2.0 5 votes vote down vote up
def _copy_resources(test_source_path, resources, default_dest_path):
    """
    Copies a list of resources to the dest_path

    :param test_source_path: the default destination path
    :param resources: a list of resources to be copied - can contain source
    path only, or a tuple of source and destination path.
    :return: None
    """
    for resource in resources:
        # Setting resource relative destination path and temp source path
        if isinstance(resource, tuple):
            resource_source_path, relative_dest_path = resource
            relative_dest_path = path.join(relative_dest_path,
                                           path.basename(resource_source_path))
        else:
            resource_source_path = resource
            relative_dest_path = path.basename(resource_source_path)

        # Setting resource source path
        if test_source_path:
            if not path.isabs(resource_source_path):
                resource_source_path = path.join(test_source_path,
                                                 resource_source_path)

        # Setting absolute destination path
        resource_dest_path = path.join(default_dest_path, relative_dest_path)

        _assure_path_exists(path.dirname(resource_dest_path))
        shutil.copyfile(resource_source_path, resource_dest_path) 
Example #24
Source File: plat_win.py    From Snu-Photo-Manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    path = get_short_path_name(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(path, len(path)+2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(result, FormatError(result), path) 
Example #25
Source File: _os.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def abspathu(path):
        """
        Version of os.path.abspath that uses the unicode representation
        of the current working directory, thus avoiding a UnicodeDecodeError
        in join when the cwd has non-ASCII characters.
        """
        if not isabs(path):
            path = join(os.getcwdu(), path)
        return normpath(path) 
Example #26
Source File: PathLib.py    From PyFlow with Apache License 2.0 5 votes vote down vote up
def isabs(path=("StringPin", "", {PinSpecifires.INPUT_WIDGET_VARIANT: "PathWidget"})):
        '''Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter.'''
        return osPath.isabs(path) 
Example #27
Source File: data.py    From sawtooth-marketplace with Apache License 2.0 5 votes vote down vote up
def load(data_path):
    if path.isabs(data_path):
        data_abs = data_path
    else:
        mkt_rel = '../../../'
        mkt_abs = path.realpath(path.join(path.dirname(__file__), mkt_rel))
        data_abs = path.join(mkt_abs, data_path)
    return yaml.load(open(data_abs, 'r')) 
Example #28
Source File: utils.py    From calmjs.parse with MIT License 5 votes vote down vote up
def normrelpath(base, target):
    """
    This function takes the base and target arguments as paths, and
    returns an equivalent relative path from base to the target, if both
    provided paths are absolute.
    """

    if not all(map(isabs, [base, target])):
        return target

    return relpath(normpath(target), dirname(normpath(base))) 
Example #29
Source File: _os.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def abspathu(path):
        """
        Version of os.path.abspath that uses the unicode representation
        of the current working directory, thus avoiding a UnicodeDecodeError
        in join when the cwd has non-ASCII characters.
        """
        if not isabs(path):
            path = join(os.getcwdu(), path)
        return normpath(path) 
Example #30
Source File: _os.py    From python with Apache License 2.0 5 votes vote down vote up
def abspathu(path):
        """
        Version of os.path.abspath that uses the unicode representation
        of the current working directory, thus avoiding a UnicodeDecodeError
        in join when the cwd has non-ASCII characters.
        """
        if not isabs(path):
            path = join(os.getcwdu(), path)
        return normpath(path)