Python os.path.normpath() Examples
The following are 30
code examples of os.path.normpath().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os.path
, or try the search function
.
Example #1
Source File: nzblnkconfig.py From nzb-monkey with MIT License | 7 votes |
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 #2
Source File: pre_save.py From substra-backend with Apache License 2.0 | 6 votes |
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 #3
Source File: util.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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
Source File: util.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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
Source File: senna.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
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
Source File: dired.py From dired with MIT License | 6 votes |
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 #7
Source File: utils.py From threadpoolctl with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: utils.py From deeper_wider_siamese_trackers with MIT License | 6 votes |
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 #9
Source File: dired_misc.py From SublimeFileBrowser with MIT License | 6 votes |
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 #10
Source File: pytest.py From clonedigger with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: templates.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #12
Source File: path.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: path.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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 #14
Source File: path.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: __init__.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: pytest.py From clonedigger with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: libopencm3.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
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 #18
Source File: path.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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
Source File: gutter_color.py From GutterColor with MIT License | 6 votes |
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 #20
Source File: guiback.py From ibeis with Apache License 2.0 | 6 votes |
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 #21
Source File: filepath.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #22
Source File: song.py From QMusic with GNU Lesser General Public License v2.1 | 6 votes |
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 #23
Source File: test_reporter.py From rsmtool with Apache License 2.0 | 5 votes |
def test_get_section_file_map_rsmeval(self): special_sections = ['placeholder'] custom_sections = ['/path/notebook.ipynb'] section_file_map = self.reporter.get_section_file_map(special_sections, custom_sections, context='rsmeval') eq_(section_file_map['data_description'], join(notebook_path, 'data_description.ipynb')) eq_(section_file_map['notebook'], '/path/notebook.ipynb') eq_(section_file_map['placeholder'], normpath('special_notebook_path/placeholder.ipynb'))
Example #24
Source File: filepath.py From learn_python3_spider with MIT License | 5 votes |
def child(self, path): """ Create and return a new L{FilePath} representing a path contained by C{self}. @param path: The base name of the new L{FilePath}. If this contains directory separators or parent references it will be rejected. @type path: L{bytes} or L{unicode} @raise InsecurePath: If the result of combining this path with C{path} would result in a path which is not a direct child of this path. @return: The child path. @rtype: L{FilePath} with a mode equal to the type of C{path}. """ colon = _coerceToFilesystemEncoding(path, ":") sep = _coerceToFilesystemEncoding(path, os.sep) ourPath = self._getPathAsSameTypeAs(path) if platform.isWindows() and path.count(colon): # Catch paths like C:blah that don't have a slash raise InsecurePath("%r contains a colon." % (path,)) norm = normpath(path) if sep in norm: raise InsecurePath("%r contains one or more directory separators" % (path,)) newpath = abspath(joinpath(ourPath, norm)) if not newpath.startswith(ourPath): raise InsecurePath("%r is not a child of %s" % (newpath, ourPath)) return self.clonePath(newpath)
Example #25
Source File: test_reporter.py From rsmtool with Apache License 2.0 | 5 votes |
def test_get_section_file_map_rsmcompare(self): special_sections = ['placeholder'] custom_sections = ['/path/notebook.ipynb'] section_file_map = self.reporter.get_section_file_map(special_sections, custom_sections, context='rsmcompare') eq_(section_file_map['evaluation'], join(comparison_notebook_path, 'evaluation.ipynb')) eq_(section_file_map['notebook'], '/path/notebook.ipynb') eq_(section_file_map['placeholder'], normpath('special_notebook_path/placeholder.ipynb'))
Example #26
Source File: mutagenTest.py From QMusic with GNU Lesser General Public License v2.1 | 5 votes |
def __init__(self, uri): super(Song, self).__init__() self.__dict__ = self from os.path import abspath, realpath, normpath self.uri = normpath(realpath(abspath(uri))) self.getTags()
Example #27
Source File: local.py From scylla with Apache License 2.0 | 5 votes |
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 #28
Source File: test_start_go_to.py From selenium-python-helium with MIT License | 5 votes |
def assertUrlEquals(self, expected, actual): expected = str(path.normpath(expected.lower().replace('\\', '/'))) actual = str(path.normpath(actual.lower().replace('\\', '/'))) self.assertEqual(expected, actual)
Example #29
Source File: test_config.py From pytest with MIT License | 5 votes |
def test_absolute_win32_path(self, testdir): temp_ini_file = testdir.makefile( ".ini", custom=""" [pytest] addopts = --version """, ) from os.path import normpath temp_ini_file = normpath(str(temp_ini_file)) ret = pytest.main(["-c", temp_ini_file]) assert ret == ExitCode.OK
Example #30
Source File: pg.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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