Python os.path.normpath() Examples

The following are code examples for showing how to use os.path.normpath(). 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: 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 2
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 3
Project: razzy-spinner   Author: rafasashi   File: senna.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep 
        
        # Verifies the existence of the executable on the self._path first    
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment 
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')  
                self._path = path.normpath(environ['SENNA']) + sep 
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        
        self.operations = operations 
Example 4
Project: misp42splunk   Author: remg427   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_appname_from_path(absolute_path):
    absolute_path = op.normpath(absolute_path)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
        except ValueError:
            continue
        else:
            try:
                if parts[idx + 1] == "etc":
                    return parts[idx - 1]
            except IndexError:
                pass
            continue
    #return None
    return "-" 
Example 5
Project: OpenBottle   Author: xiaozhuchacha   File: senna.py    MIT License 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep

        # Verifies the existence of the executable on the self._path first
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')
                self._path = path.normpath(environ['SENNA']) + sep
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))

        self.operations = operations 
Example 6
Project: OpenBottle   Author: xiaozhuchacha   File: senna.py    MIT License 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep

        # Verifies the existence of the executable on the self._path first
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')
                self._path = path.normpath(environ['SENNA']) + sep
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))

        self.operations = operations 
Example 7
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 8
Project: Health-Checker   Author: KriAga   File: senna.py    MIT License 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep

        # Verifies the existence of the executable on the self._path first
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')
                self._path = path.normpath(environ['SENNA']) + sep
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))

        self.operations = operations 
Example 9
Project: platzi-hello-gae   Author: xertica-cloud   File: fileadmin.py    GNU General Public License v2.0 6 votes vote down vote up
def _normalize_path(self, path):
        """
            Verify and normalize path.

            If the path is not relative to the base directory, will raise a 404 exception.

            If the path does not exist, this will also raise a 404 exception.
        """
        base_path = self.get_base_path()

        if path is None:
            directory = base_path
            path = ''
        else:
            path = op.normpath(path)
            directory = op.normpath(op.join(base_path, path))

            if not self.is_in_folder(base_path, directory):
                abort(404)

        if not op.exists(directory):
            abort(404)

        return base_path, directory, path 
Example 10
Project: apio   Author: FPGAwars   File: util.py    GNU General Public License v2.0 6 votes vote down vote up
def resolve_packages(packages, installed_packages, spec_packages):
    bin_dirs = setup_environment()

    # -- Check packages
    check = True
    for package in packages:
        version = installed_packages.get(package, {}).get('version', '')
        spec_version = spec_packages.get(package, '')
        check &= check_package(
            package,
            version,
            spec_version,
            bin_dirs.get(package))

    # -- Load packages
    if check:
        global scons_command
        scons_command = [normpath(sys.executable),
                         safe_join(bin_dirs.get('scons'), 'scons')]

    return check 
Example 11
Project: bonsai   Author: git-afsantos   File: py_parser.py    MIT License 6 votes vote down vote up
def make_absolute(self, importing_path, imported_module):
        leading_dots = ''.join(takewhile(lambda c: c == '.',
                                         iter(imported_module)))
        parent_path = path.join(leading_dots[:2],
                                *('..' for _ in leading_dots[2:]))
        entity_name = imported_module[len(leading_dots):]

        if parent_path:
            file_dir = (path.dirname(importing_path)
                        if path.isfile(importing_path)
                        else importing_path)
            pythonpath = [path.normpath(path.join(file_dir, parent_path))]
        else:
            pythonpath = self.pythonpath

        return entity_name, pythonpath 
Example 12
Project: nzb-monkey   Author: nzblnk   File: nzblnkconfig.py    MIT License 6 votes vote down vote up
def config_win():

    try:
        import winreg as reg
        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk')
        reg.SetValue(key, '', reg.REG_SZ, 'URL:nzblnk')
        reg.SetValueEx(key, 'URL Protocol', 0, reg.REG_SZ, '')
        reg.CloseKey(key)

        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk\\shell\\open\\command')
        reg.SetValue(key, '', reg.REG_SZ, '"{0}" "%1"'.format(op.normpath(os.path.abspath(sys.executable))))
        reg.CloseKey(key)

    except (OSError, ImportError):
        print(Col.FAIL + ' FAILED to setup registry link for NZBLNK scheme!' + Col.OFF)
        sleep(wait_time)
        sys.exit(2) 
Example 13
Project: GTDWeb   Author: lanbing510   File: templates.py    GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 14
Project: xdoctest   Author: Erotemic   File: util_path.py    Apache License 2.0 6 votes vote down vote up
def ensuredir(dpath, mode=0o1777):
    """
    Ensures that directory will exist. creates new dir with sticky bits by
    default

    Args:
        dpath (str): dir to ensure. Can also be a tuple to send to join
        mode (int): octal mode of directory (default 0o1777)

    Returns:
        str: path - the ensured directory
    """
    if isinstance(dpath, (list, tuple)):  # nocover
        dpath = join(*dpath)
    if not exists(dpath):
        try:
            os.makedirs(normpath(dpath), mode=mode)
        except OSError:  # nocover
            raise
    return dpath 
Example 15
Project: sublime-text-3-packages   Author: nickjj   File: gutter_color.py    MIT License 6 votes vote down vote up
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False):
  """Change the color scheme in the given Settings to a background-corrected one"""
  from os.path import join, normpath, isfile

  settings = load_settings(settings_file)
  settings_scheme = settings.get("color_scheme")
  if current_scheme == settings_scheme:
    new_scheme_path =  join(packages_path(), normpath(new_scheme[len("Packages/"):]))
    if isfile(new_scheme_path) and not regenerate:
      settings.set("color_scheme", new_scheme)
    else:
      generate_scheme_fix(current_scheme, new_scheme_path)
      settings.set("color_scheme", new_scheme)
    save_settings(settings_file)
    return True
  return False 
Example 16
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    MIT License 6 votes vote down vote up
def rev_parse_manifest_path(self, cwd):
        """
        Search parent directories for package.json.

        Starting at the current working directory. Go up one directory
        at a time checking if that directory contains a package.json
        file. If it does, return that directory.

        """

        name = 'package.json'
        manifest_path = path.normpath(path.join(cwd, name))

        bin_path = path.join(cwd, 'node_modules/.bin/')

        if path.isfile(manifest_path) and path.isdir(bin_path):
            return manifest_path

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.rev_parse_manifest_path(parent) 
Example 17
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    MIT License 6 votes vote down vote up
def find_local_cmd_path(self, cmd):
        """
        Find a local binary in node_modules/.bin.

        Given package.json filepath and a local binary to find,
        look in node_modules/.bin for that binary.

        """

        cwd = path.dirname(self.manifest_path)

        binary = self.get_pkg_bin_cmd(cmd)

        if binary:
            return path.normpath(path.join(cwd, binary))

        return self.find_ancestor_cmd_path(cmd, cwd) 
Example 18
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    MIT License 6 votes vote down vote up
def find_ancestor_cmd_path(self, cmd, cwd):
        """Recursively check for command binary in ancestors' node_modules/.bin directories."""

        node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))

        binary = path.join(node_modules_bin, cmd)

        if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
            binary += '.cmd'

        if binary and access(binary, X_OK):
            return binary

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.find_ancestor_cmd_path(cmd, parent) 
Example 19
Project: sublime-text-3-packages   Author: nickjj   File: st_color_scheme_matcher.py    MIT License 6 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        self.plist_file = color_filter(
            readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                    sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                )
            )
        )
        self.scheme_file = scheme_file
        self.matched = {}

        self.parse_scheme() 
Example 20
Project: rpython-lang-scheme   Author: tomoh1r   File: local.py    MIT License 6 votes vote down vote up
def __init__(self, path=None, expanduser=False):
        """ Initialize and return a local Path instance.

        Path can be relative to the current directory.
        If path is None it defaults to the current working directory.
        If expanduser is True, tilde-expansion is performed.
        Note that Path instances always carry an absolute path.
        Note also that passing in a local path object will simply return
        the exact same path object. Use new() to get a new copy.
        """
        if path is None:
            self.strpath = py.error.checked_call(os.getcwd)
        elif isinstance(path, common.PathBase):
            self.strpath = path.strpath
        elif isinstance(path, py.builtin._basestring):
            if expanduser:
                path = os.path.expanduser(path)
            self.strpath = abspath(normpath(path))
        else:
            raise ValueError("can only pass None, Path instances "
                             "or non-empty strings to LocalPath") 
Example 21
Project: git_for_splunk   Author: ChrisYounger   File: util.py    Apache License 2.0 6 votes vote down vote up
def get_appname_from_path(absolute_path):
    absolute_path = op.normpath(absolute_path)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
        except ValueError:
            continue
        else:
            try:
                if parts[idx + 1] == "etc":
                    return parts[idx - 1]
            except IndexError:
                pass
            continue
    #return None
    return "-" 
Example 22
Project: SRLTagger   Author: jawahar273   File: srlnltk.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, path_, encoding='utf-8'):
        """

        """
        if  not super(SennaSRLTagger, self).SUPPORTED_OPERATIONS.count('srl'): 
            super(SennaSRLTagger, self).SUPPORTED_OPERATIONS.append('srl')
        super(SennaSRLTagger, self).SUPPORTED_OPERATIONS.append('srl')
        super(SennaSRLTagger, self).__init__(path_,  ['srl'], encoding)
        self.operations =  ['srl']
        self._path = path.normpath(path_) + sep
        self._encoding = encoding
        
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')
                self._path = path.normpath(environ['SENNA']) + sep
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        #""" 
Example 23
Project: open-recipe   Author: dspray95   File: filepath.py    The Unlicense 6 votes vote down vote up
def preauthChild(self, path):
        """
        Use me if C{path} might have slashes in it, but you know they're safe.

        @param path: A relative path (ie, a path not starting with C{"/"})
            which will be interpreted as a child or descendant of this path.
        @type path: L{bytes} or L{unicode}

        @return: The child path.
        @rtype: L{FilePath} with a mode equal to the type of C{path}.
        """
        ourPath = self._getPathAsSameTypeAs(path)

        newpath = abspath(joinpath(ourPath, normpath(path)))
        if not newpath.startswith(ourPath):
            raise InsecurePath("%s is not a child of %s" %
                               (newpath, ourPath))
        return self.clonePath(newpath) 
Example 24
Project: sublime-win-bak   Author: okoala   File: node_linter.py    MIT License 6 votes vote down vote up
def rev_parse_manifest_path(self, cwd):
        """
        Search parent directories for package.json.

        Starting at the current working directory. Go up one directory
        at a time checking if that directory contains a package.json
        file. If it does, return that directory.

        """

        name = 'package.json'
        manifest_path = path.normpath(path.join(cwd, name))

        bin_path = path.join(cwd, 'node_modules/.bin/')

        if path.isfile(manifest_path) and path.isdir(bin_path):
            return manifest_path

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.rev_parse_manifest_path(parent) 
Example 25
Project: sublime-win-bak   Author: okoala   File: node_linter.py    MIT License 6 votes vote down vote up
def find_local_cmd_path(self, cmd):
        """
        Find a local binary in node_modules/.bin.

        Given package.json filepath and a local binary to find,
        look in node_modules/.bin for that binary.

        """

        cwd = path.dirname(self.manifest_path)

        binary = self.get_pkg_bin_cmd(cmd)

        if binary:
            return path.normpath(path.join(cwd, binary))

        return self.find_ancestor_cmd_path(cmd, cwd) 
Example 26
Project: sublime-win-bak   Author: okoala   File: node_linter.py    MIT License 6 votes vote down vote up
def find_ancestor_cmd_path(self, cmd, cwd):
        """Recursively check for command binary in ancestors' node_modules/.bin directories."""

        node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))

        binary = path.join(node_modules_bin, cmd)

        if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
            binary += '.cmd'

        if binary and access(binary, X_OK):
            return binary

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.find_ancestor_cmd_path(cmd, parent) 
Example 27
Project: swift-android-buildtools   Author: readdle   File: resources.py    MIT License 6 votes vote down vote up
def get_all_files_rec(srcs):
    res = []
    for src in srcs:
        base = path.normpath(path.join(src, path.pardir))
        if path.isfile(src):
            res.append(
                {
                    "into": path.normpath(path.join(src[len(base) + 1:], path.pardir)),
                    "base": base,
                    "files": [src]
                }
            )
        else:
            for root, dirs, files in os.walk(src):
                if len(files) > 0:
                    res.append(
                        {  # TestData/Input/Resource1/file1, TestData/Input/Resource1/file2
                            "into": path.normpath(path.join(path.join(root, files[0])[len(base) + 1:], path.pardir)),
                        # Resource1
                            "base": base,  # TestData/Input/
                            "files": [path.join(root, f) for f in files]  # [file1, file2]
                        }
                    )

    return res 
Example 28
Project: rpm2swidtag   Author: swidtags   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def resolve_path(base, target):
	return normpath(join(dirname(base), target)) 
Example 29
Project: calmjs   Author: calmjs   File: toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def _generate_transpile_target(self, spec, target):
        # ensure that the target is fully normalized.
        bd_target = join(spec[BUILD_DIR], normpath(target))
        self._validate_build_target(spec, bd_target)
        if not exists(dirname(bd_target)):
            logger.debug("creating dir '%s'", dirname(bd_target))
            makedirs(dirname(bd_target))

        return bd_target 
Example 30
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 31
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def make_archive(self):
        ensure_dirname_exists(self.path)

        if self.output:
            output_path = self.get_output()
            if exists(output_path):
                os.utime(output_path, None)

        with Archiver(self.path, kind='tar') as arc:
            files = set()

            def archive_and_copy(name, arcname):
                assert arcname not in files, arcname
                files.add(arcname)

                arc.zf.add(name, arcname=arcname)

                if self.output:
                    dest = join(self.get_output(), arcname)
                    # Make path separators consistent for string compare
                    dest = normpath(dest)
                    name = normpath(name)
                    if name != dest:
                        ensure_dirname_exists(dest)
                        shutil.copy2(name, dest)

            for d in self.archived_deps():
                if d.isNativeProject() or d.isArchivableProject():
                    arc_prefix = ''
                    if self.auto_prefix and d.isPlatformDependent():
                        arc_prefix = self.platformName().replace('_', '-')
                    for file_path, arc_name in d.getArchivableResults(self.relpath):
                        archive_and_copy(file_path, join(arc_prefix, arc_name))
                elif hasattr(d, 'getResults') and not d.getResults():
                    logv("[{}: ignoring dependency {} with no results]".format(self.name, d.name))
                else:
                    abort('Unsupported dependency for native distribution {}: {}'.format(self.name, d.name))

        self.notify_updated() 
Example 32
Project: rebel-framework   Author: reb311ion   File: BaseReport.py    GNU General Public License v3.0 5 votes vote down vote up
def open(self):
        from os import name as os_name

        if os_name == "nt":
            from os.path import normpath, dirname
            from os import makedirs

            output = normpath(self.output)
            makedirs(dirname(output), exist_ok=True)

            self.output = output

        self.file = open(self.output, 'w+') 
Example 33
Project: project_generator_definitions   Author: project-generator   File: definitions.py    Apache License 2.0 5 votes vote down vote up
def get_mcu_record(self, target):
        if target in self.get_targets():
            mcu_path = self.targets[target]['mcu']
            mcu_path = normpath(mcu_path)
            mcu_path = join(dirname(__file__), mcu_path) + '.yaml'
            return _load_record(mcu_path)
        else:
            return None 
Example 34
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 35
Project: py   Author: pytest-dev   File: local.py    MIT License 5 votes vote down vote up
def new(self, **kw):
        """ create a modified version of this path.
            the following keyword arguments modify various path parts::

              a:/some/path/to/a/file.ext
              xx                           drive
              xxxxxxxxxxxxxxxxx            dirname
                                xxxxxxxx   basename
                                xxxx       purebasename
                                     xxx   ext
        """
        obj = object.__new__(self.__class__)
        if not kw:
            obj.strpath = self.strpath
            return obj
        drive, dirname, basename, purebasename,ext = self._getbyspec(
             "drive,dirname,basename,purebasename,ext")
        if 'basename' in kw:
            if 'purebasename' in kw or 'ext' in kw:
                raise ValueError("invalid specification %r" % kw)
        else:
            pb = kw.setdefault('purebasename', purebasename)
            try:
                ext = kw['ext']
            except KeyError:
                pass
            else:
                if ext and not ext.startswith('.'):
                    ext = '.' + ext
            kw['basename'] = pb + ext

        if ('dirname' in kw and not kw['dirname']):
            kw['dirname'] = drive
        else:
            kw.setdefault('dirname', dirname)
        kw.setdefault('sep', self.sep)
        obj.strpath = normpath(
            "%(dirname)s%(sep)s%(basename)s" % kw)
        return obj 
Example 36
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 37
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pg.py    MIT License 5 votes vote down vote up
def get_library_dirs(self):
            """List of compiler library directories."""
            opt = FCompiler.get_library_dirs(self)
            flang_dir = dirname(self.executables['compiler_f77'][0])
            opt.append(normpath(join(flang_dir, '..', 'lib')))

            return opt 
Example 38
Project: platzi-hello-gae   Author: xertica-cloud   File: fileadmin.py    GNU General Public License v2.0 5 votes vote down vote up
def get_base_path(self):
        """
            Return base path. Override to customize behavior (per-user
            directories, etc)
        """
        return op.normpath(self.base_path) 
Example 39
Project: platzi-hello-gae   Author: xertica-cloud   File: fileadmin.py    GNU General Public License v2.0 5 votes vote down vote up
def is_in_folder(self, base_path, directory):
        """
            Verify that `directory` is in `base_path` folder

            :param base_path:
                Base directory path
            :param directory:
                Directory path to check
        """
        return op.normpath(directory).startswith(base_path) 
Example 40
Project: recruit   Author: Frank-qlu   File: pg.py    Apache License 2.0 5 votes vote down vote up
def get_library_dirs(self):
            """List of compiler library directories."""
            opt = FCompiler.get_library_dirs(self)
            flang_dir = dirname(self.executables['compiler_f77'][0])
            opt.append(normpath(join(flang_dir, '..', 'lib')))

            return opt 
Example 41
Project: codimension   Author: SergeySatskiy   File: findinfiles.py    GNU General Public License v3.0 5 votes vote down vote up
def __selectDirClicked(self):
        """The user selects a directory"""
        options = QFileDialog.Options()
        options |= QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog
        dirName = QFileDialog.getExistingDirectory(
            self, 'Select directory to search in',
            self.dirEditCombo.currentText(), options)

        if dirName:
            self.dirEditCombo.setEditText(normpath(dirName))
        self.__testSearchability() 
Example 42
Project: Alexa-Ecovacs   Author: EtienneMD   File: local.py    MIT License 5 votes vote down vote up
def new(self, **kw):
        """ create a modified version of this path.
            the following keyword arguments modify various path parts::

              a:/some/path/to/a/file.ext
              xx                           drive
              xxxxxxxxxxxxxxxxx            dirname
                                xxxxxxxx   basename
                                xxxx       purebasename
                                     xxx   ext
        """
        obj = object.__new__(self.__class__)
        if not kw:
            obj.strpath = self.strpath
            return obj
        drive, dirname, basename, purebasename,ext = self._getbyspec(
             "drive,dirname,basename,purebasename,ext")
        if 'basename' in kw:
            if 'purebasename' in kw or 'ext' in kw:
                raise ValueError("invalid specification %r" % kw)
        else:
            pb = kw.setdefault('purebasename', purebasename)
            try:
                ext = kw['ext']
            except KeyError:
                pass
            else:
                if ext and not ext.startswith('.'):
                    ext = '.' + ext
            kw['basename'] = pb + ext

        if ('dirname' in kw and not kw['dirname']):
            kw['dirname'] = drive
        else:
            kw.setdefault('dirname', dirname)
        kw.setdefault('sep', self.sep)
        obj.strpath = normpath(
            "%(dirname)s%(sep)s%(basename)s" % kw)
        return obj 
Example 43
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 44
Project: pywhdfs   Author: yassineazzouz   File: client.py    MIT License 5 votes vote down vote up
def resolvepath(self, hdfs_path):
    """Return absolute, normalized path.
    :param hdfs_path: Remote path.
    """
    path = hdfs_path
    if not psp.isabs(path):
      if not self.root or not psp.isabs(self.root):
        root = self._api_request(method='GET', hdfs_path='/', params={'op': 'GETHOMEDIRECTORY'}).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)
    _logger.debug('Resolved path %r to %r.', hdfs_path, path)
    return path 
Example 45
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 46
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 47
Project: denite-extra   Author: neoclide   File: project.py    MIT License 5 votes vote down vote up
def on_init(self, context):
        folders = self.vim.vars.get('project_folders', [])
        context['__folders'] = [util.expand(normpath(x)) for x in folders] 
Example 48
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def open_file_path(fn):
    """
    Formats a path as /C/some/path/on/windows/no/colon.txt that is suitable to
    be passed as the `file` arg to the `open_file` command.
    """
    fn = normpath(fn)
    fn = re.sub('^([a-zA-Z]):', '/\\1', fn)
    fn = re.sub(r'\\', '/', fn)
    return fn 
Example 49
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def find_and_open_file(f):
    """
    Looks in open windows for `f` and focuses the related view.
    Opens file if not found. Returns associated view in both cases.
    """
    for w in sublime.windows():
        for v in w.views():
            if normpath(f) == v.file_name():
                w.focus_view(v)
                return v

    return sublime.active_window().open_file(f)

#################################### HELPERS ################################### 
Example 50
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)