Python os.path.isabs() Examples

The following are code examples for showing how to use os.path.isabs(). 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: spleeter   Author: deezer   File: __init__.py    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: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def _safe_path(path):
    """
    If not on Windows, this function returns `path`.
    Otherwise, it return a potentially transformed path that is safe for file operations.
    This works around the MAX_PATH limit on Windows:
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
    """
    if is_windows():
        if _opts.verbose and '/' in path:
            warn("Forward slash in path on windows: {}".format(path))
            import traceback
            traceback.print_stack()
        path = normpath(path)
        if isabs(path):
            if path.startswith('\\\\'):
                if path[2:].startswith('?\\'):
                    # if it already has a \\?\ don't do the prefix
                    pass
                else:
                    # only a UNC path has a double slash prefix
                    path = '\\\\?\\UNC' + path
            else:
                path = '\\\\?\\' + path
        path = _unicode(path)
    return path 
Example 3
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def _verify_layout(self):
        output = realpath(self.get_output())
        for destination, sources in self.layout.items():
            if not isinstance(destination, str):
                abort("Destination (layout keys) should be a string", context=self)
            if not isinstance(sources, list):
                sources = [sources]
            if not destination:
                abort("Destination (layout keys) can not be empty", context=self)
            for source in sources:
                if not isinstance(source, (str, dict)):
                    abort("Error in '{}': sources should be strings or dicts".format(destination), context=self)
            if isabs(destination):
                abort("Invalid destination: '{}': destination should not be absolute".format(destination), context=self)
            final_destination = normpath(join(output, destination))
            if not final_destination.startswith(output):
                abort("Invalid destination: '{}': destination should not escape the output directory ('{}' is not in '{}')".format(destination, final_destination, output), context=self)
            if not destination.endswith('/'):
                if len(sources) > 1:
                    abort("Invalid layout: cannot copy multiple files to a single destination: '{dest}'\n"
                          "Should the destination be a directory: '{dest}/'? (note the trailing slash)".format(dest=destination), context=self)
                if len(sources) < 1:
                    abort("Invalid layout: no file to copy to '{dest}'\n"
                          "Do you want an empty directory: '{dest}/'? (note the trailing slash)".format(dest=destination), context=self) 
Example 4
Project: dired   Author: kublaios   File: dired.py    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 5
Project: lrcloud   Author: madsbk   File: metafile.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file_path):
        self.file_path = file_path
        config = cparser.ConfigParser()
        config.read(file_path)
        logging.info("Read meta-data file: %s"%file_path)
        self._data = {}
        for sec in config.sections():
            self._data[sec] = {}
            for (name, value) in config.items(sec):
                if value == "True":
                    value = True
                elif value == "False":
                    value = False
                try:# Try to convert the value to a time object
                   t = datetime.strptime(value, DATETIME_FORMAT)
                   value = t
                except ValueError:
                    pass
                except TypeError:
                    pass
                if name == "filename" and not isabs(value):
                    value = join(dirname(file_path), value) # Make filenames absolute
                self._data[sec][name] = value 
Example 6
Project: mmdetection   Author: CBN-code-release   File: philly_env.py    Apache License 2.0 6 votes vote down vote up
def abspath(path, roots=None):
    """Expand ~ to VC's home and resolve relative paths to absolute paths
    :param path: the path to resolve
    :type path: str
    :param roots: CWD roots to resolve relative paths to them
    :type roots: list
    """
    path = expand_vc_user(path)
    if op.isabs(path):
        return path
    if not roots:
        roots = ["~"]
    roots = [expand_vc_user(root) for root in roots]
    for root in roots:
        resolved = op.abspath(op.join(root, path))
        if op.isfile(resolved) or op.isdir(resolved):
            return resolved
    # return assuming the first root (even though it does not exist)
    return op.abspath(op.join(roots[0], path)) 
Example 7
Project: pipeline   Author: liorbenhorin   File: plat_win.py    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 8
Project: conf   Author: XonqNopp   File: pytest.py    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 absolute path, it was probably loaded locally
        # during the tests
        if not osp.isabs(modfile) or modfile.startswith(testdir):
            del sys.modules[modname] 
Example 9
Project: conf   Author: XonqNopp   File: pytest.py    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 absolute path, it was probably loaded locally
        # during the tests
        if not osp.isabs(modfile) or modfile.startswith(testdir):
            del sys.modules[modname] 
Example 10
Project: cohorts   Author: hammerlab   File: utils.py    Apache License 2.0 6 votes vote down vote up
def get_cache_dir(cache_dir, cache_root_dir=None, *args, **kwargs):
    """
    Return full cache_dir, according to following logic:
        - if cache_dir is a full path (per path.isabs), return that value
        - if not and if cache_root_dir is not None, join two paths
        - otherwise, log warnings and return None
    Separately, if args or kwargs are given, format cache_dir using kwargs
    """
    cache_dir = cache_dir.format(*args, **kwargs)
    if path.isabs(cache_dir):
        if cache_root_dir is not None:
            logger.warning('cache_dir ({}) is a full path; ignoring cache_root_dir'.format(cache_dir))
        return cache_dir
    if cache_root_dir is not None:
        return path.join(cache_root_dir, cache_dir)
    else:
        logger.warning("cache dir is not full path & cache_root_dir not given. Caching may not work as expected!")
    return None 
Example 11
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 12
Project: rowgenerators   Author: Metatab   File: file.py    MIT License 5 votes vote down vote up
def get_target(self):
        """Return the url of the target file in the local file system.
        """
        from os.path import isabs, join, normpath

        t = self.clone()

        if not isabs(t.fspath) and self.working_dir:
            t.path = normpath(join(self.working_dir, t.fspath))

        return t 
Example 13
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def relpath_or_absolute(path, start, prefix=""):
    """
    Finds a relative path and joins it to 'prefix', or otherwise tries to use 'path' as an absolute path.
    If 'path' is not an absolute path, an error is thrown.
    """
    try:
        return join(prefix, os.path.relpath(path, start))
    except ValueError:
        if not os.path.isabs(path):
            raise ValueError('can not find a relative path to dependency and path is not absolute: ' + path)
        return path 
Example 14
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def walk(d):
        """
        Convenience method to implement getResults() by including all files under a directory.
        """
        assert isabs(d)
        results = []
        for root, _, files in os.walk(d):
            for name in files:
                path = join(root, name)
                results.append(path)
        return results 
Example 15
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def get_source_path(self, jdk):
        """
        Gets the path where the sources for this library are located.

        :param JDKConfig jdk: the JDK against which a relative path is resolved
        :return: the absolute path where the sources of this library are located
        """
        if self.sourcePath is None:
            return None
        if isabs(self.sourcePath):
            return self.sourcePath
        path = self.get_jdk_path(jdk, self.sourcePath)
        if not exists(path) and jdk.javaCompliance >= self.jdkStandardizedSince:
            return self.get_jdk_path(jdk, 'lib/src.zip')
        return path 
Example 16
Project: openhatch   Author: campbe13   File: project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def data_path(path):
    """If path is relative, return the given path inside the project data dir,
    otherwise return the path unmodified
    """
    return path if isabs(path) else join(project_data_dir(), path) 
Example 17
Project: chattR   Author: patrickstocklin   File: _os.py    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 18
Project: py   Author: pytest-dev   File: local.py    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 19
Project: py   Author: pytest-dev   File: local.py    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 20
Project: pygitpraise   Author: ylmrx   File: git_praise.py    The Unlicense 5 votes vote down vote up
def praise(revision, files):
    '''Sometimes you have no-one to blame, spread the love.'''

    repo = Repo('.', search_parent_directories=True)
    init()
    colors =  [Fore.MAGENTA, Fore.LIGHTGREEN_EX, Fore.RED, Fore.BLUE, Fore.CYAN, Fore.GREEN]
    heart_names = [':blue_heart:', ':green_heart:', ':yellow_heart:', ':purple_heart:', ':orange_heart:']
    hearts = [emoji.emojize(heart) for heart in heart_names]
    knowns = {}

    for file in files:
        abs_filepath = file if path.isabs(file) else path.join(getcwd(), file)
        blames = repo.blame(revision, abs_filepath)

        for blame in blames:
            for line in blame[1]:
                email = blame[0].author.email
                if email not in knowns.keys():
                    knowns[email] = [ choice(hearts), choice(colors) ]
                if blame[0].hexsha == b'0000000000000000000000000000000000000000'.decode():
                    print("%s %s%s %s %s : %s%s" %
                        ('0' * 8,
                        emoji.emojize(':broken_heart:') * 5,
                        Fore.YELLOW,
                        " ---- Not commited yet! ---- ",
                        emoji.emojize(':broken_heart:') * 5,
                        line,
                        Fore.RESET
                        )
                        )
                else:
                    print("%s %s %s %s - %s %s %s : %s" % 
                        (blame[0].hexsha[:8],
                        knowns[email][0],
                        knowns[email][1],
                        blame[0].author.name[:15].ljust(15, ' '),
                        blame[0].committed_datetime,
                        Fore.RESET,
                        knowns[email][0],
                        line)) 
Example 21
Project: FlaskBackend   Author: iamrajhans   File: main.py    MIT License 5 votes vote down vote up
def _do_load_config(application, filename, silent=False):
    """Load configuration to the application.

    Args:
        application: Flask application
        filename: Configuration name or file path.
        silent: Don't raise exception if the config is not present.
    """
    filename = op.expanduser(op.expandvars(filename))

    if not filename.endswith('.py'):
        filename += '.py'

    if filename.startswith('.'):
        filename = op.abspath(filename)

    if not op.isabs(filename):
        # Load /<app_root>/config/<filename>
        filename = op.join(application.root_path, 'config', filename)

    if not silent or op.exists(filename):
        application.logger.info('Loading configuration [%s] ...', filename)

    if not silent and not op.exists(filename):
        raise MissingConfigurationError(filename)

    application.config.from_pyfile(filename, silent=silent)

    # See load_config().
    application._loaded_config_list.append(filename) 
Example 22
Project: codimension   Author: SergeySatskiy   File: pixmapcache.py    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 23
Project: codimension   Author: SergeySatskiy   File: findinfiles.py    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 24
Project: Alexa-Ecovacs   Author: EtienneMD   File: local.py    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 25
Project: Alexa-Ecovacs   Author: EtienneMD   File: local.py    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 26
Project: TESTGIT   Author: B-ROY   File: _os.py    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 27
Project: AneMo   Author: jspargo   File: _os.py    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 28
Project: GTDWeb   Author: lanbing510   File: _os.py    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 29
Project: SwiftMeter   Author: SwifterSwift   File: meter.py    MIT License 5 votes vote down vote up
def output_full_path(output_file_path):
    if output_file_path is not None:
        if path.isdir(output_file_path):
            output_file_path = path.join(output_file_path, 'report.txt')
        if path.isabs(output_file_path): 
            return output_file_path
        else: 
            current_dir = path.dirname(__file__)
            return path.join(current_dir, output_file_path)
    return None 
Example 30
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    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 31
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    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 32
Project: python-netsurv   Author: sofia-netsurv   File: local.py    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 33
Project: python-netsurv   Author: sofia-netsurv   File: local.py    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 34
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    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 35
Project: python-netsurv   Author: sofia-netsurv   File: local.py    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 36
Project: python-netsurv   Author: sofia-netsurv   File: local.py    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 37
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_common.py    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 38
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_common.py    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 
Example 39
Project: liberator   Author: libscie   File: _os.py    Creative Commons Zero v1.0 Universal 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 40
Project: rpython-lang-scheme   Author: tomoh1r   File: local.py    MIT License 5 votes vote down vote up
def samefile(self, other):
        """ return True if 'other' references the same file as 'self'.
        """
        other = getattr(other, "strpath", 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 41
Project: rpython-lang-scheme   Author: tomoh1r   File: local.py    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 = [getattr(arg, "strpath", 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)
        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 + sep + arg
        obj = object.__new__(self.__class__)
        obj.strpath = normpath(strpath)
        return obj 
Example 42
Project: sniffer   Author: threathunterX   File: run_driver.py    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 43
Project: 2019-1-OSS-L1   Author: 19-1-skku-oss   File: pathlib.py    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 44
Project: open-recipe   Author: dspray95   File: project.py    The Unlicense 5 votes vote down vote up
def data_path(path, createdir=False):
    """
    Return the given path joined with the .scrapy data directory.
    If given an absolute path, return it unmodified.
    """
    if not isabs(path):
        if inside_project():
            path = join(project_data_dir(), path)
        else:
            path = join('.scrapy', path)
    if createdir and not exists(path):
        os.makedirs(path)
    return path 
Example 45
Project: open-recipe   Author: dspray95   File: filepath.py    The Unlicense 5 votes vote down vote up
def isabs(self):
        """
        Check if this L{FilePath} refers to an absolute path.

        This always returns C{True}.

        @return: C{True}, always.
        @rtype: L{bool}
        """
        return isabs(self.path) 
Example 46
Project: vnpy_crypto   Author: birforce   File: test_common.py    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 47
Project: vnpy_crypto   Author: birforce   File: test_common.py    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 
Example 48
Project: Fun5G   Author: OpenWinCon   File: _os.py    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 49
Project: Vigtech-Services   Author: VigTech   File: _os.py    GNU Lesser General Public License v3.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 50
Project: DroidPot   Author: WhySoGeeky   File: _os.py    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)