Python posixpath.isabs() Examples

The following are 30 code examples of posixpath.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 posixpath , or try the search function .
Example #1
Source File: utils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def read_file(filename: str, binary: bool = False) -> typing.Any:
    """Get the contents of a file contained with qutebrowser.

    Args:
        filename: The filename to open as string.
        binary: Whether to return a binary string.
                If False, the data is UTF-8-decoded.

    Return:
        The file contents as string.
    """
    assert not posixpath.isabs(filename), filename
    assert os.path.pardir not in filename.split(posixpath.sep), filename

    if not binary and filename in _resource_cache:
        return _resource_cache[filename]

    if hasattr(sys, 'frozen'):
        # PyInstaller doesn't support pkg_resources :(
        # https://github.com/pyinstaller/pyinstaller/wiki/FAQ#misc
        fn = os.path.join(os.path.dirname(sys.executable), filename)
        if binary:
            with open(fn, 'rb') as f:  # type: typing.IO
                return f.read()
        else:
            with open(fn, 'r', encoding='utf-8') as f:
                return f.read()
    else:
        data = pkg_resources.resource_string(
            qutebrowser.__name__, filename)

        if binary:
            return data

        return data.decode('UTF-8') 
Example #2
Source File: hdfio.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def open(self, h5_rel_path):
        """
        Create an HDF5 group and enter this specific group. If the group exists in the HDF5 path only the h5_path is
        set correspondingly otherwise the group is created first.

        Args:
            h5_rel_path (str): relative path from the current HDF5 path - h5_path - to the new group

        Returns:
            FileHDFio: FileHDFio object pointing to the new group
        """
        new_h5_path = self.copy()
        if os.path.isabs(h5_rel_path):
            raise ValueError(
                "Absolute paths are not supported -> replace by relative path name!"
            )

        if h5_rel_path.strip() == ".":
            h5_rel_path = ""
        if h5_rel_path.strip() != "":
            new_h5_path.h5_path = posixpath.join(new_h5_path.h5_path, h5_rel_path)
        new_h5_path.history.append(h5_rel_path)

        return new_h5_path 
Example #3
Source File: basepath.py    From bfg9000 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, path, root=Root.builddir, destdir=False):
        if destdir and isinstance(root, Root):
            raise ValueError('destdir only applies to install paths')
        drive, path = self.__normalize(path, expand_user=True)

        if posixpath.isabs(path):
            root = Root.absolute
            destdir = False
        elif root == Root.absolute:
            raise ValueError("'{}' is not absolute".format(path))
        elif isinstance(root, BasePath):
            path = self.__join(root.suffix, path)
            destdir = root.destdir
            root = root.root

        if ( path == posixpath.pardir or
             path.startswith(posixpath.pardir + posixpath.sep) ):
            raise ValueError("too many '..': path cannot escape root")

        self.suffix = drive + path
        self.root = root
        self.destdir = destdir 
Example #4
Source File: files.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def canonical_filename(filename):
    """Return a canonical file name for `filename`.

    An absolute path with no redundant components and normalized case.

    """
    if filename not in CANONICAL_FILENAME_CACHE:
        if not os.path.isabs(filename):
            for path in [os.curdir] + sys.path:
                if path is None:
                    continue
                f = os.path.join(path, filename)
                try:
                    exists = os.path.exists(f)
                except UnicodeError:
                    exists = False
                if exists:
                    filename = f
                    break
        cf = abs_file(filename)
        CANONICAL_FILENAME_CACHE[filename] = cf
    return CANONICAL_FILENAME_CACHE[filename] 
Example #5
Source File: files.py    From coveragepy with Apache License 2.0 6 votes vote down vote up
def canonical_filename(filename):
    """Return a canonical file name for `filename`.

    An absolute path with no redundant components and normalized case.

    """
    if filename not in CANONICAL_FILENAME_CACHE:
        cf = filename
        if not os.path.isabs(filename):
            for path in [os.curdir] + sys.path:
                if path is None:
                    continue
                f = os.path.join(path, filename)
                try:
                    exists = os.path.exists(f)
                except UnicodeError:
                    exists = False
                if exists:
                    cf = f
                    break
        cf = abs_file(cf)
        CANONICAL_FILENAME_CACHE[filename] = cf
    return CANONICAL_FILENAME_CACHE[filename] 
Example #6
Source File: test_posixpath.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #7
Source File: test_posixpath.py    From android_universal with MIT License 5 votes vote down vote up
def test_path_isabs(self):
        self.assertPathEqual(self.path.isabs) 
Example #8
Source File: test_posixpath.py    From android_universal with MIT License 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertIs(posixpath.isabs(b""), False)
        self.assertIs(posixpath.isabs(b"/"), True)
        self.assertIs(posixpath.isabs(b"/foo"), True)
        self.assertIs(posixpath.isabs(b"/foo/bar"), True)
        self.assertIs(posixpath.isabs(b"foo/bar"), False) 
Example #9
Source File: basepath.py    From bfg9000 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def append(self, path):
        drive, path = self.__normalize(path, expand_user=True)
        if not posixpath.isabs(path):
            path = self.__join(self.suffix, path)
        return type(self)(drive + path, self.root, self.destdir) 
Example #10
Source File: basepath.py    From bfg9000 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __normalize(path, expand_user=False):
        if expand_user:
            path = os.path.expanduser(path)
        drive, path = ntpath.splitdrive(path)
        if drive and not ntpath.isabs(path):
            raise ValueError('relative paths with drives not supported')

        drive = drive.replace('\\', '/')
        path = posixpath.normpath(path.replace('\\', '/'))
        if path == posixpath.curdir:
            path = ''
        return drive, path 
Example #11
Source File: test_posixpath.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #12
Source File: test_posixpath.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertRaises(TypeError, posixpath.isabs) 
Example #13
Source File: test_posixpath.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertIs(posixpath.isabs(b""), False)
        self.assertIs(posixpath.isabs(b"/"), True)
        self.assertIs(posixpath.isabs(b"/foo"), True)
        self.assertIs(posixpath.isabs(b"/foo/bar"), True)
        self.assertIs(posixpath.isabs(b"foo/bar"), False) 
Example #14
Source File: test_posixpath.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #15
Source File: validation.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def validate_path(path, ctx=None):
  ctx = ctx or validation.Context.raise_on_error(prefix='Invalid path: ')
  if not path:
    ctx.error('not specified')
    return
  if posixpath.isabs(path):
    ctx.error('must not be absolute: %s', path)
  if any(p in ('.', '..') for p in path.split(posixpath.sep)):
    ctx.error('must not contain ".." or "." components: %s', path) 
Example #16
Source File: files.py    From coveragepy with Apache License 2.0 5 votes vote down vote up
def isabs_anywhere(filename):
    """Is `filename` an absolute path on any OS?"""
    return ntpath.isabs(filename) or posixpath.isabs(filename) 
Example #17
Source File: test_posixpath.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertIs(posixpath.isabs(b""), False)
        self.assertIs(posixpath.isabs(b"/"), True)
        self.assertIs(posixpath.isabs(b"/foo"), True)
        self.assertIs(posixpath.isabs(b"/foo/bar"), True)
        self.assertIs(posixpath.isabs(b"foo/bar"), False) 
Example #18
Source File: test_posixpath.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertIs(posixpath.isabs(b""), False)
        self.assertIs(posixpath.isabs(b"/"), True)
        self.assertIs(posixpath.isabs(b"/foo"), True)
        self.assertIs(posixpath.isabs(b"/foo/bar"), True)
        self.assertIs(posixpath.isabs(b"foo/bar"), False) 
Example #19
Source File: adb_compatibility_devicetest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testShell_externalStorageDefined(self):
    under_test = self.getTestInstance()
    external_storage = under_test.Shell('echo $EXTERNAL_STORAGE')
    self.assertIsInstance(external_storage, str)
    self.assertTrue(posixpath.isabs(external_storage)) 
Example #20
Source File: adb_compatibility_devicetest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testShell_externalStorageDefined(self):
    under_test = self.getTestInstance()
    external_storage = under_test.Shell('echo $EXTERNAL_STORAGE')
    self.assertIsInstance(external_storage, str)
    self.assertTrue(posixpath.isabs(external_storage)) 
Example #21
Source File: adb_compatibility_devicetest.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testShell_externalStorageDefined(self):
    under_test = self.getTestInstance()
    external_storage = under_test.Shell('echo $EXTERNAL_STORAGE')
    self.assertIsInstance(external_storage, str)
    self.assertTrue(posixpath.isabs(external_storage)) 
Example #22
Source File: files.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def isabs_anywhere(filename):
    """Is `filename` an absolute path on any OS?"""
    return ntpath.isabs(filename) or posixpath.isabs(filename) 
Example #23
Source File: _filename.py    From pathvalidate with MIT License 5 votes vote down vote up
def validate_abspath(self, value: str) -> None:
        if any([ntpath.isabs(value), posixpath.isabs(value)]):
            raise ValidationError(
                description="found an absolute path ({}), expected a filename".format(value),
                platform=self.platform,
                reason=ErrorReason.FOUND_ABS_PATH,
            ) 
Example #24
Source File: _filepath.py    From pathvalidate with MIT License 5 votes vote down vote up
def validate_abspath(self, value: PathType) -> None:
        value = str(value)
        is_posix_abs = posixpath.isabs(value)
        is_nt_abs = ntpath.isabs(value)
        err_object = ValidationError(
            description=(
                "an invalid absolute file path ({}) for the platform ({}).".format(
                    value, self.platform.value
                )
                + " to avoid the error, specify an appropriate platform correspond"
                + " with the path format, or 'auto'."
            ),
            platform=self.platform,
            reason=ErrorReason.MALFORMED_ABS_PATH,
        )

        if any([self._is_windows() and is_nt_abs, self._is_linux() and is_posix_abs]):
            return

        if self._is_universal() and any([is_posix_abs, is_nt_abs]):
            ValidationError(
                description=(
                    "{}. expected a platform independent file path".format(
                        "POSIX absolute file path found"
                        if is_posix_abs
                        else "NT absolute file path found"
                    )
                ),
                platform=self.platform,
                reason=ErrorReason.MALFORMED_ABS_PATH,
            )

        if any([self._is_windows(), self._is_universal()]) and is_posix_abs:
            raise err_object

        drive, _tail = ntpath.splitdrive(value)
        if not self._is_windows() and drive and is_nt_abs:
            raise err_object 
Example #25
Source File: hdfio.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def h5_path(self, path):
        """
        Set the path in the HDF5 file starting from the root group

        Args:
            path (str): HDF5 path
        """
        if (path is None) or (path == ""):
            path = "/"
        self._h5_path = posixpath.normpath(path)
        if not posixpath.isabs(self._h5_path):
            self._h5_path = "/" + self._h5_path
        self._h5_group = "store.root" + self._h5_path.replace("/", ".")
        if self._h5_group[-1] != ".":
            self._h5_group += "." 
Example #26
Source File: hdfio.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, file_name, h5_path="/", mode="a"):
        if not os.path.isabs(file_name):
            raise ValueError("file_name must be given as absolute path name")
        self._file_name = None
        self.file_name = file_name
        self.history = []
        self.h5_path = h5_path
        self._filter = ["groups", "nodes", "objects"] 
Example #27
Source File: test_posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #28
Source File: test_posixpath.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #29
Source File: test_posixpath.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False) 
Example #30
Source File: client.py    From hdfs with MIT License 4 votes vote down vote up
def resolve(self, hdfs_path):
    """Return absolute, normalized path, with special markers expanded.

    :param hdfs_path: Remote path.

    Currently supported markers:

    * `'#LATEST'`: this marker gets expanded to the most recently updated file
      or folder. They can be combined using the `'{N}'` suffix. For example,
      `'foo/#LATEST{2}'` is equivalent to `'foo/#LATEST/#LATEST'`.

    """
    path = hdfs_path
    if not psp.isabs(path):
      if not self.root or not psp.isabs(self.root):
        root = self._get_home_directory('/').json()['Path']
        self.root = psp.join(root, self.root) if self.root else root
        _logger.debug('Updated root to %r.', self.root)
      path = psp.join(self.root, path)
    path = psp.normpath(path)

    def expand_latest(match):
      """Substitute #LATEST marker."""
      prefix = match.string[:match.start()]
      suffix = ''
      n = match.group(1) # n as in {N} syntax
      for _ in repeat(None, int(n) if n else 1):
        statuses = self._list_status(psp.join(prefix, suffix)).json()
        candidates = sorted([
          (-status['modificationTime'], status['pathSuffix'])
          for status in statuses['FileStatuses']['FileStatus']
        ])
        if not candidates:
          raise HdfsError('Cannot expand #LATEST. %r is empty.', prefix)
        elif len(candidates) == 1 and candidates[0][1] == '':
          raise HdfsError('Cannot expand #LATEST. %r is a file.', prefix)
        suffix = psp.join(suffix, candidates[0][1])
      return '/' + suffix

    path = re.sub(r'/?#LATEST(?:{(\d+)})?(?=/|$)', expand_latest, path)
    # #LATEST expansion (could cache the pattern, but not worth it)

    _logger.debug('Resolved path %r to %r.', hdfs_path, path)
    return path