Python os.path.normpath() Examples

The following are 30 code examples for showing how to use os.path.normpath(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: razzy-spinner   Author: rafasashi   File: senna.py    License: 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 2
Project: misp42splunk   Author: remg427   File: util.py    License: 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 3
Project: misp42splunk   Author: remg427   File: util.py    License: 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 4
Project: dired   Author: kublaios   File: dired.py    License: MIT License 6 votes vote down vote up
def _move(self, path):
        if path == self.path:
            return

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

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

        # Move all items into the target directory.  If the target directory was also selected,
        # ignore it.
        files = self.get_marked() or self.get_selected()
        path = normpath(path)
        for filename in files:
            fqn = normpath(join(self.path, filename))
            if fqn != path:
                shutil.move(fqn, path)
        self.view.run_command('dired_refresh') 
Example 5
Project: nzb-monkey   Author: nzblnk   File: nzblnkconfig.py    License: 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 6
Project: SublimeFileBrowser   Author: aziz   File: dired_misc.py    License: MIT License 6 votes vote down vote up
def vcs_colorized(self, changed_items):
        '''called on main thread'''
        if not self.view.settings().has('dired_index'):
            return  # view was closed
        modified, untracked = [], []
        files_regions = dict((f, r) for f, r in zip(self.get_all(), self.view.split_by_newlines(Region(0, self.view.size()))))
        colorblind = self.view.settings().get('vcs_color_blind', False)
        offset = 1 if not colorblind else 0
        for fn in changed_items.keys():
            full_fn = normpath(fn)
            r = files_regions.get(full_fn, 0)
            if r:
                icon   = self._get_name_point(r) - 2
                r      = Region(icon, icon + offset)
                status = changed_items[fn]
                if status == 'M':
                    modified.append(r)
                elif status == '?':
                    untracked.append(r)
        if colorblind:
            self.view.add_regions('M', modified, 'item.colorblind.dired', '', MARK_OPTIONS | sublime.DRAW_EMPTY_AS_OVERWRITE)
            self.view.add_regions('?', untracked, 'item.colorblind.dired', '', MARK_OPTIONS | sublime.DRAW_EMPTY)
        else:
            self.view.add_regions('M', modified, 'item.modified.dired', '', MARK_OPTIONS)
            self.view.add_regions('?', untracked, 'item.untracked.dired', '', MARK_OPTIONS) 
Example 7
Project: GTDWeb   Author: lanbing510   File: templates.py    License: 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 8
Project: web2board   Author: bq   File: libopencm3.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_source_files(src_dir):
    mkdata = parse_makefile_data(join(src_dir, "Makefile"))

    for include in mkdata['includes']:
        _mkdata = parse_makefile_data(normpath(join(src_dir, include)))
        for key, value in _mkdata.iteritems():
            for v in value:
                if v not in mkdata[key]:
                    mkdata[key].append(v)

    sources = []
    lib_root = env.subst("$PLATFORMFW_DIR")
    for obj_file in mkdata['objs']:
        src_file = obj_file[:-1] + "c"
        for search_path in mkdata['vpath']:
            src_path = normpath(join(src_dir, search_path, src_file))
            if isfile(src_path):
                sources.append(join("$BUILD_DIR", "FrameworkLibOpenCM3",
                                    src_path.replace(lib_root + sep, "")))
                break
    return sources 
Example 9
Project: GutterColor   Author: ggordan   File: gutter_color.py    License: 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 10
Project: Safejumper-for-Desktop   Author: proxysh   File: filepath.py    License: GNU General Public License v2.0 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 11
Project: ibeis   Author: Erotemic   File: guiback.py    License: Apache License 2.0 6 votes vote down vote up
def update_state(self):
        workdir = ut.truepath(self.workdir_row.edit.text())
        dbname = self.dbname_row.edit.text()
        current_choice = normpath(join(workdir, dbname))
        workdir_exists = ut.checkpath(workdir, verbose=False)
        print('workdir_exists = %r' % (workdir_exists,))
        if workdir_exists:
            if ut.checkpath(current_choice, verbose=False):
                self.current_row.edit.setColorFG((0, 0, 255))
                self.create_but.setText('Open existing database')
            else:
                self.current_row.edit.setColorFG(None)
                self.create_but.setText('Create in workdir')
            self.create_but.setEnabled(True)
        else:
            self.current_row.edit.setColorFG((255, 0, 0))
            self.create_but.setText('Create in workdir')
            self.create_but.setEnabled(False)
        self.current_row.edit.setText(current_choice) 
Example 12
Project: substra-backend   Author: SubstraFoundation   File: pre_save.py    License: Apache License 2.0 6 votes vote down vote up
def data_sample_pre_save(sender, instance, **kwargs):
    destination_path = path.join(getattr(settings, 'MEDIA_ROOT'), 'datasamples/{0}'.format(instance.pk))
    src_path = normpath(instance.path)

    if path.exists(destination_path):
        raise FileExistsError(f'File exists: {destination_path}')

    # try to make an hard link to keep a free copy of the data
    # if not possible, keep the real path location
    try:
        shutil.copytree(src_path, destination_path, copy_function=link)
    except Exception:
        logger.exception(f'error happened while copying data from {src_path} to {destination_path}')
        shutil.rmtree(destination_path, ignore_errors=True)
        logger.info(f'directory {destination_path} deleted')
    else:
        # override path for getting our hardlink
        instance.path = destination_path 
Example 13
Project: QMusic   Author: dragondjf   File: song.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, url):
        super(Song, self).__init__()
        self.__dict__ = self
        for key in TAG_KEYS:
            if key in ['tracknumber', 'discnumber']:
                self[key] = 0
            elif key in ['title', 'artist', 'album']:
                self[key] = "unknown"

        from os.path import abspath, realpath, normpath
        self['url'] = normpath(realpath(abspath(url)))
        self['folder'] = os.path.dirname(self['url'])

        if self.isExisted():
            try:
                self.getTags()
            except Exception, e:
                logger.error(e) 
Example 14
Project: Fluid-Designer   Author: Microvellum   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def main():
    import sys

    # Possibly temp. addons path
    from os.path import join, dirname, normpath
    sys.path.append(normpath(join(dirname(__file__),
                                  "..", "..", "addons", "modules")))
    sys.path.append(join(utils.user_resource('SCRIPTS'),
                         "addons", "modules"))

    # fake module to allow:
    #   from bpy.types import Panel
    sys.modules.update({
        "bpy.app": app,
        "bpy.app.handlers": app.handlers,
        "bpy.app.translations": app.translations,
        "bpy.types": types,
    })

    # Initializes Python classes.
    # (good place to run a profiler or trace).
    utils.load_scripts() 
Example 15
Project: Fluid-Designer   Author: Microvellum   File: path.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False 
Example 16
Project: Fluid-Designer   Author: Microvellum   File: path.py    License: GNU General Public License v3.0 6 votes vote down vote up
def reduce_dirs(dirs):
    """
    Given a sequence of directories, remove duplicates and
    any directories nested in one of the other paths.
    (Useful for recursive path searching).

    :arg dirs: Sequence of directory paths.
    :type dirs: sequence
    :return: A unique list of paths.
    :rtype: list
    """
    dirs = list({_os.path.normpath(_os.path.abspath(d)) for d in dirs})
    dirs.sort(key=lambda d: len(d))
    for i in range(len(dirs) - 1, -1, -1):
        for j in range(i):
            print(i, j)
            if len(dirs[i]) == len(dirs[j]):
                break
            elif is_subdir(dirs[i], dirs[j]):
                del dirs[i]
                break
    return dirs 
Example 17
Project: Fluid-Designer   Author: Microvellum   File: path.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False 
Example 18
Project: Fluid-Designer   Author: Microvellum   File: path.py    License: GNU General Public License v3.0 6 votes vote down vote up
def reduce_dirs(dirs):
    """
    Given a sequence of directories, remove duplicates and
    any directories nested in one of the other paths.
    (Useful for recursive path searching).

    :arg dirs: Sequence of directory paths.
    :type dirs: sequence
    :return: A unique list of paths.
    :rtype: list
    """
    dirs = list({_os.path.normpath(_os.path.abspath(d)) for d in dirs})
    dirs.sort(key=lambda d: len(d))
    for i in range(len(dirs) - 1, -1, -1):
        for j in range(i):
            print(i, j)
            if len(dirs[i]) == len(dirs[j]):
                break
            elif is_subdir(dirs[i], dirs[j]):
                del dirs[i]
                break
    return dirs 
Example 19
Project: clonedigger   Author: jlachowski   File: pytest.py    License: GNU General Public License v3.0 6 votes vote down vote up
def project_root(parser, projdir=os.getcwd()):
    """try to find project's root and add it to sys.path"""
    curdir = osp.abspath(projdir)
    previousdir = curdir
    testercls = PyTester
    conf_file_path = osp.join(curdir, CONF_FILE)
    if osp.isfile(conf_file_path):
        testercls = load_pytest_conf(conf_file_path, parser)
    while this_is_a_testdir(curdir) or \
              osp.isfile(osp.join(curdir, '__init__.py')):
        newdir = osp.normpath(osp.join(curdir, os.pardir))
        if newdir == curdir:
            break
        previousdir = curdir
        curdir = newdir
        conf_file_path = osp.join(curdir, CONF_FILE)
        if osp.isfile(conf_file_path):
            testercls = load_pytest_conf(conf_file_path, parser)
    return previousdir, testercls 
Example 20
Project: clonedigger   Author: jlachowski   File: pytest.py    License: GNU General Public License v3.0 6 votes vote down vote up
def load_django_settings(self, dirname):
        """try to find project's setting and load it"""
        curdir = osp.abspath(dirname)
        previousdir = curdir
        while not osp.isfile(osp.join(curdir, 'settings.py')) and \
                  osp.isfile(osp.join(curdir, '__init__.py')):
            newdir = osp.normpath(osp.join(curdir, os.pardir))
            if newdir == curdir:
                raise AssertionError('could not find settings.py')
            previousdir = curdir
            curdir = newdir
        # late django initialization
        settings = load_module_from_modpath(modpath_from_file(osp.join(curdir, 'settings.py')))
        from django.core.management import setup_environ
        setup_environ(settings)
        settings.DEBUG = False
        self.settings = settings
        # add settings dir to pythonpath since it's the project's root
        if curdir not in sys.path:
            sys.path.insert(1, curdir) 
Example 21
Project: plantweb   Author: carlos-jenkins   File: test_plantweb_args.py    License: Apache License 2.0 6 votes vote down vote up
def test_args():

    examples_dir = normpath(join(abspath(dirname(__file__)), '../examples/'))
    sources = [
        join(examples_dir, src)
        for src in listdir(examples_dir)
        if src.endswith('.uml')
    ]

    parsed = args.parse_args(sources + ['-vvvv'])

    assert parsed.verbose == 4
    assert parsed.sources == sources

    assert parsed.engine is None
    assert parsed.format is None
    assert parsed.server == 'http://plantuml.com/plantuml/'

    assert not parsed.no_cache
    assert parsed.cache_dir == '~/.cache/plantweb' 
Example 22
Project: threadpoolctl   Author: joblib   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def threadpool_info_from_subprocess(module):
    """Utility to call threadpool_info in a subprocess

    `module` is imported before calling threadpool_info
    """
    # set PYTHONPATH to import from non sub-modules
    path1 = normpath(dirname(threadpoolctl.__file__))
    path2 = os.path.join(path1, "tests", "_openmp_test_helper")
    pythonpath = os.pathsep.join([path1, path2])
    env = os.environ.copy()
    try:
        env["PYTHONPATH"] = os.pathsep.join([pythonpath, env["PYTHONPATH"]])
    except KeyError:
        env["PYTHONPATH"] = pythonpath

    cmd = [sys.executable, "-m", "threadpoolctl", "-i", module]
    out = check_output(cmd, env=env).decode("utf-8")
    return json.loads(out) 
Example 23
Project: deeper_wider_siamese_trackers   Author: cvpr2019   File: utils.py    License: MIT License 6 votes vote down vote up
def load_video(video):
    # buffer controls whether load all images
    info = {}
    info[video] = {}

    base_path = normpath(join(realpath(dirname(__file__)), '../dataset', video))

    # ground truth
    gt_path = join(base_path, 'groundtruth_rect.txt')
    gt = np.loadtxt(gt_path, delimiter=',')
    gt = gt - [1, 1, 0, 0]   # OTB for python (if video not from OTB, please delete it)

    # img file name
    img_path = join(base_path, 'img', '*jpg')
    image_files = sorted(glob.glob(img_path))

    # info summary
    info[video]['name'] = video
    info[video]['image_files'] = [normpath(join(base_path, 'img', im_f)) for im_f in image_files]
    info[video]['gt'] = gt

    return info


## for loading pretrained model 
Example 24
Project: calmjs   Author: calmjs   File: toolchain.py    License: 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 25
Project: qtsass   Author: spyder-ide   File: __init__.py    License: MIT License 5 votes vote down vote up
def example(*paths):
    """Get path to an example."""

    return normpath(join(dirname(__file__), '..', 'examples', *paths)) 
Example 26
Project: hsds   Author: HDFGroup   File: fileClient.py    License: Apache License 2.0 5 votes vote down vote up
def _getFilePath(self, bucket, key=''):
        filepath = pp.join(self._root_dir, bucket, key)
        return pp.normpath(filepath) 
Example 27
Project: project_generator_definitions   Author: project-generator   File: definitions.py    License: 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 28
Project: py   Author: pytest-dev   File: local.py    License: 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 29
Project: py   Author: pytest-dev   File: local.py    License: MIT License 5 votes vote down vote up
def join(self, *args, **kwargs):
        """ return a new path by appending all 'args' as path
        components.  if abs=1 is used restart from root if any
        of the args is an absolute path.
        """
        sep = self.sep
        strargs = [fspath(arg) for arg in args]
        strpath = self.strpath
        if kwargs.get('abs'):
            newargs = []
            for arg in reversed(strargs):
                if isabs(arg):
                    strpath = arg
                    strargs = newargs
                    break
                newargs.insert(0, arg)
        # special case for when we have e.g. strpath == "/"
        actual_sep = "" if strpath.endswith(sep) else sep
        for arg in strargs:
            arg = arg.strip(sep)
            if iswin32:
                # allow unix style paths even on windows.
                arg = arg.strip('/')
                arg = arg.replace('/', sep)
            strpath = strpath + actual_sep + arg
            actual_sep = sep
        obj = object.__new__(self.__class__)
        obj.strpath = normpath(strpath)
        return obj 
Example 30
Project: recruit   Author: Frank-qlu   File: pg.py    License: 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