Python os.path.isabs() Examples

The following are 30 code examples for showing how to use os.path.isabs(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os.path , or try the search function .

Example 1
Project: spleeter   Author: deezer   File: __init__.py    License: MIT License 6 votes vote down vote up
def get(self, model_directory):
        """ Ensures required model is available at given location.

        :param model_directory: Expected model_directory to be available.
        :raise IOError: If model can not be retrieved.
        """
        # Expend model directory if needed.
        if not isabs(model_directory):
            model_directory = join(self.DEFAULT_MODEL_PATH, model_directory)
        # Download it if not exists.
        model_probe = join(model_directory, self.MODEL_PROBE_PATH)
        if not exists(model_probe):
            if not exists(model_directory):
                makedirs(model_directory)
                self.download(
                    model_directory.split(sep)[-1],
                    model_directory)
                self.writeProbe(model_directory)
        return model_directory 
Example 2
Project: dired   Author: kublaios   File: dired.py    License: 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 3
Project: pipeline   Author: liorbenhorin   File: plat_win.py    License: 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 4
Project: clonedigger   Author: jlachowski   File: pytest.py    License: 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
Project: incubator-retired-cotton   Author: apache   File: sandbox.py    License: 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 6
Project: luscan-devel   Author: blackye   File: localfile.py    License: 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 7
Project: collectd-cloudwatch   Author: awslabs   File: setup.py    License: 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 8
Project: EasyClangComplete   Author: niosus   File: file.py    License: 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 9
Project: EasyClangComplete   Author: niosus   File: cmake_file.py    License: 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 10
Project: DSAlign   Author: mozilla   File: stats.py    License: 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 11
Project: hdl_checker   Author: suoto   File: test_base_server.py    License: 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 12
Project: mealpy   Author: edmundmok   File: venv_update.py    License: 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 13
Project: hsds   Author: HDFGroup   File: fileClient.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, app):

        self._app = app
        self._root_dir = config.get("root_dir")
        if not self._root_dir:
            log.error("FileClient init: root_dir config not set")
            raise HTTPInternalServerError()
        if not pp.isdir(self._root_dir):
            log.error("FileClient init: root folder does not exist")
            raise HTTPInternalServerError()
        if not pp.isabs(self._root_dir):
            log.error("FileClient init: root dir most have absolute path")
            raise HTTPInternalServerError() 
Example 14
Project: hsds   Author: HDFGroup   File: fileClient.py    License: Apache License 2.0 5 votes vote down vote up
def _validateBucket(self, bucket):
        if not bucket or pp.isabs(bucket) or pp.dirname(bucket):
            msg = "invalid bucket name"
            log.warn(msg)
            raise HTTPBadRequest(reason=msg) 
Example 15
Project: hsds   Author: HDFGroup   File: fileClient.py    License: Apache License 2.0 5 votes vote down vote up
def _validateKey(self, key):
        if not key or pp.isabs(key):
            msg = "invalid key name"
            log.warn(msg)
            raise HTTPBadRequest(reason=msg) 
Example 16
Project: py   Author: pytest-dev   File: local.py    License: MIT License 5 votes vote down vote up
def samefile(self, other):
        """ return True if 'other' references the same file as 'self'.
        """
        other = fspath(other)
        if not isabs(other):
            other = abspath(other)
        if self == other:
            return True
        if not hasattr(os.path, "samefile"):
            return False
        return py.error.checked_call(
                os.path.samefile, self.strpath, other) 
Example 17
Project: py   Author: pytest-dev   File: local.py    License: MIT License 5 votes vote down vote up
def join(self, *args, **kwargs):
        """ return a new path by appending all 'args' as path
        components.  if abs=1 is used restart from root if any
        of the args is an absolute path.
        """
        sep = self.sep
        strargs = [fspath(arg) for arg in args]
        strpath = self.strpath
        if kwargs.get('abs'):
            newargs = []
            for arg in reversed(strargs):
                if isabs(arg):
                    strpath = arg
                    strargs = newargs
                    break
                newargs.insert(0, arg)
        # special case for when we have e.g. strpath == "/"
        actual_sep = "" if strpath.endswith(sep) else sep
        for arg in strargs:
            arg = arg.strip(sep)
            if iswin32:
                # allow unix style paths even on windows.
                arg = arg.strip('/')
                arg = arg.replace('/', sep)
            strpath = strpath + actual_sep + arg
            actual_sep = sep
        obj = object.__new__(self.__class__)
        obj.strpath = normpath(strpath)
        return obj 
Example 18
Project: codimension   Author: SergeySatskiy   File: pixmapcache.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getPath(self, path):
        """Provides an absolute path"""
        if isabs(path):
            return path if exists(path) else None

        if self.__searchDirs is None:
            self.__initSearchDirs()

        for dirName in self.__searchDirs:
            fullPath = dirName + path
            if exists(fullPath):
                return fullPath
        return None 
Example 19
Project: codimension   Author: SergeySatskiy   File: searchsupport.py    License: GNU General Public License v3.0 5 votes vote down vote up
def search(self, expression):
        """Perform search within this item"""
        self.matches = []
        if self.bufferUUID != "":
            # Search item is the currently loaded buffer
            mainWindow = GlobalData().mainWindow
            widget = mainWindow.getWidgetByUUID(self.bufferUUID)
            if widget is not None:
                # Search in the buffer

                self.__lookThroughLines(widget.getEditor().lines, expression)
                return

        # Here: there were no buffer or have not found it
        #       try searching in a file
        if not isabs(self.fileName) or not exists(self.fileName):
            # Unfortunately not all network file systems report the
            # fact that a file has been deleted from the disk so
            # let's simply ignore such files
            return

        # File exists, search in the file
        try:
            content = getFileContent(self.fileName).splitlines()
            self.__lookThroughLines(content, expression)
        except Exception as exc:
            logging.error('Error searching in %s: %s', self.fileName, str(exc)) 
Example 20
Project: GTDWeb   Author: lanbing510   File: _os.py    License: 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 21
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    License: MIT License 5 votes vote down vote up
def resolve_from_str(input, root):
    assert not isinstance(input, Path), "would break on py2"
    root = Path(root)
    input = expanduser(input)
    input = expandvars(input)
    if isabs(input):
        return Path(input)
    else:
        return root.joinpath(input) 
Example 22
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    License: MIT License 5 votes vote down vote up
def fnmatch_ex(pattern, path):
    """FNMatcher port from py.path.common which works with PurePath() instances.

    The difference between this algorithm and PurePath.match() is that the latter matches "**" glob expressions
    for each part of the path, while this algorithm uses the whole path instead.

    For example:
        "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py" with this algorithm, but not with
        PurePath.match().

    This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according
    this logic.

    References:
    * https://bugs.python.org/issue29249
    * https://bugs.python.org/issue34731
    """
    path = PurePath(path)
    iswin32 = sys.platform.startswith("win")

    if iswin32 and sep not in pattern and posix_sep in pattern:
        # Running on Windows, the pattern has no Windows path separators,
        # and the pattern has one or more Posix path separators. Replace
        # the Posix path separators with the Windows path separator.
        pattern = pattern.replace(posix_sep, sep)

    if sep not in pattern:
        name = path.name
    else:
        name = str(path)
        if path.is_absolute() and not os.path.isabs(pattern):
            pattern = "*{}{}".format(os.sep, pattern)
    return fnmatch.fnmatch(name, pattern) 
Example 23
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def samefile(self, other):
        """ return True if 'other' references the same file as 'self'.
        """
        other = fspath(other)
        if not isabs(other):
            other = abspath(other)
        if self == other:
            return True
        if iswin32:
            return False # there is no samefile
        return py.error.checked_call(
                os.path.samefile, self.strpath, other) 
Example 24
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def join(self, *args, **kwargs):
        """ return a new path by appending all 'args' as path
        components.  if abs=1 is used restart from root if any
        of the args is an absolute path.
        """
        sep = self.sep
        strargs = [fspath(arg) for arg in args]
        strpath = self.strpath
        if kwargs.get('abs'):
            newargs = []
            for arg in reversed(strargs):
                if isabs(arg):
                    strpath = arg
                    strargs = newargs
                    break
                newargs.insert(0, arg)
        # special case for when we have e.g. strpath == "/"
        actual_sep = "" if strpath.endswith(sep) else sep
        for arg in strargs:
            arg = arg.strip(sep)
            if iswin32:
                # allow unix style paths even on windows.
                arg = arg.strip('/')
                arg = arg.replace('/', sep)
            strpath = strpath + actual_sep + arg
            actual_sep = sep
        obj = object.__new__(self.__class__)
        obj.strpath = normpath(strpath)
        return obj 
Example 25
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    License: MIT License 5 votes vote down vote up
def fnmatch_ex(pattern, path):
    """FNMatcher port from py.path.common which works with PurePath() instances.

    The difference between this algorithm and PurePath.match() is that the latter matches "**" glob expressions
    for each part of the path, while this algorithm uses the whole path instead.

    For example:
        "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py" with this algorithm, but not with
        PurePath.match().

    This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according
    this logic.

    References:
    * https://bugs.python.org/issue29249
    * https://bugs.python.org/issue34731
    """
    path = PurePath(path)
    iswin32 = sys.platform.startswith("win")

    if iswin32 and sep not in pattern and posix_sep in pattern:
        # Running on Windows, the pattern has no Windows path separators,
        # and the pattern has one or more Posix path separators. Replace
        # the Posix path separators with the Windows path separator.
        pattern = pattern.replace(posix_sep, sep)

    if sep not in pattern:
        name = path.name
    else:
        name = str(path)
        if path.is_absolute() and not os.path.isabs(pattern):
            pattern = "*{}{}".format(os.sep, pattern)
    return fnmatch.fnmatch(name, pattern) 
Example 26
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def samefile(self, other):
        """ return True if 'other' references the same file as 'self'.
        """
        other = fspath(other)
        if not isabs(other):
            other = abspath(other)
        if self == other:
            return True
        if iswin32:
            return False # there is no samefile
        return py.error.checked_call(
                os.path.samefile, self.strpath, other) 
Example 27
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def join(self, *args, **kwargs):
        """ return a new path by appending all 'args' as path
        components.  if abs=1 is used restart from root if any
        of the args is an absolute path.
        """
        sep = self.sep
        strargs = [fspath(arg) for arg in args]
        strpath = self.strpath
        if kwargs.get('abs'):
            newargs = []
            for arg in reversed(strargs):
                if isabs(arg):
                    strpath = arg
                    strargs = newargs
                    break
                newargs.insert(0, arg)
        # special case for when we have e.g. strpath == "/"
        actual_sep = "" if strpath.endswith(sep) else sep
        for arg in strargs:
            arg = arg.strip(sep)
            if iswin32:
                # allow unix style paths even on windows.
                arg = arg.strip('/')
                arg = arg.replace('/', sep)
            strpath = strpath + actual_sep + arg
            actual_sep = sep
        obj = object.__new__(self.__class__)
        obj.strpath = normpath(strpath)
        return obj 
Example 28
Project: sniffer   Author: threathunterX   File: run_driver.py    License: Apache License 2.0 5 votes vote down vote up
def lnk_http_bro(src, dst):
    u""" 创建http.bro脚本link """
    # 只能支持绝对路径
    assert path.isabs(src) and path.isabs(dst), "link http.bro需要使用绝对路径"

    symlink(src, dst) 
Example 29
Project: vnpy_crypto   Author: birforce   File: test_common.py    License: MIT License 5 votes vote down vote up
def test_expand_user(self):
        filename = '~/sometest'
        expanded_name = common._expand_user(filename)

        assert expanded_name != filename
        assert isabs(expanded_name)
        assert os.path.expanduser(filename) == expanded_name 
Example 30
Project: vnpy_crypto   Author: birforce   File: test_common.py    License: MIT License 5 votes vote down vote up
def test_get_filepath_or_buffer_with_path(self):
        filename = '~/sometest'
        filepath_or_buffer, _, _, should_close = common.get_filepath_or_buffer(
            filename)
        assert filepath_or_buffer != filename
        assert isabs(filepath_or_buffer)
        assert os.path.expanduser(filename) == filepath_or_buffer
        assert not should_close