我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.isabs()。
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)
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 is works around the MAX_PATH limit on Windows: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath """ if get_os() == 'windows': 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 return path
def find_submodule_git_dir(d): """Search for a submodule repo.""" if is_git_dir(d): return d try: with open(d) as fp: content = fp.read().rstrip() except (IOError, OSError): # it's probably not a file pass else: if content.startswith('gitdir: '): path = content[8:] if Git.is_cygwin(): ## Cygwin creates submodules prefixed with `/cygdrive/...` suffixes. path = decygpath(path) if not osp.isabs(path): path = osp.join(osp.dirname(d), path) return find_submodule_git_dir(path) # end handle exception return None
def _to_relative_path(cls, parent_repo, path): """:return: a path guaranteed to be relative to the given parent-repository :raise ValueError: if path is not contained in the parent repository's working tree""" path = to_native_path_linux(path) if path.endswith('/'): path = path[:-1] # END handle trailing slash if osp.isabs(path): working_tree_linux = to_native_path_linux(parent_repo.working_tree_dir) if not path.startswith(working_tree_linux): raise ValueError("Submodule checkout path '%s' needs to be within the parents repository at '%s'" % (working_tree_linux, path)) path = path[len(working_tree_linux) + 1:] if not path: raise ValueError("Absolute submodule path '%s' didn't yield a valid relative path" % path) # end verify converted relative path makes sense # end convert to a relative path return path
def _cygexpath(drive, path): if osp.isabs(path) and not drive: ## Invoked from `cygpath()` directly with `D:Apps\123`? # It's an error, leave it alone just slashes) p = path else: p = path and osp.normpath(osp.expandvars(osp.expanduser(path))) if osp.isabs(p): if drive: # Confusing, maybe a remote system should expand vars. p = path else: p = cygpath(p) elif drive: p = '/cygdrive/%s/%s' % (drive.lower(), p) return p.replace('\\', '/')
def __get_cmake_deps(deps_file): """Parse dependencies from Makefile.cmake. Args: deps_file (str): Full path to Makefile.cmake file. Returns: str[]: List of full paths to dependency files. """ folder = path.dirname(path.dirname(deps_file)) deps = [] with open(deps_file, 'r') as f: content = f.read() found = CMakeFile._DEP_REGEX.findall(content) for dep in found: if not path.isabs(dep): dep = path.join(folder, dep) deps.append(dep) return deps
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
def __async_gather_candidates(self, context, timeout): outs, errs = context['__proc'].communicate(timeout=timeout) if errs: self.error_message(context, errs) context['is_async'] = not context['__proc'].eof() if context['__proc'].eof(): context['__proc'] = None if not outs: return [] if isabs(outs[0]): candidates = [{ 'word': relpath(x, start=context['__directory']), 'action__path': x, } for x in outs if x != ''] else: candidates = [{ 'word': x, 'action__path': join(context['__directory'], x), } for x in outs if x != ''] context['__current_candidates'] += candidates if (len(context['__current_candidates']) >= self.vars['min_cache_files']): self.__cache[context['__directory']] = context[ '__current_candidates'] return candidates
def fill_judge_context(judge_context, params): judge_context.problem_id = params.problem judge_context.programming_language = params.language file_path = None if path.isabs(params.source): file_path = params.source else: file_path = path.join(path.dirname(__file__), params.source) file = open(file_path, "r") content = "".join(file.readlines()) judge_context.source_code = content file.close()
def search(cls, name, lookup=[]): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if not lookup: lookup = ['.'] if isabs(name) and isfile(name): return abspath(name) for spath in lookup: spath = abspath(spath) + os.sep fname = abspath(join(spath, name)) if not fname.startswith(spath): continue if isfile(fname): return fname for ext in cls.extensions: if isfile('%s.%s' % (fname, ext)): return '%s.%s' % (fname, ext)
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]
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')
def find_executable(name, names=None, required=True): """Utility function to find an executable in PATH name: program to find. Use given value if absolute path names: list of additional names. For instance >>> find_executable('sed', names=['gsed']) required: If True, then the function raises an Exception if the program is not found. """ path_from_env = os.environ.get(name.upper()) if path_from_env is not None: return path_from_env names = [name] + (names or []) for _name in names: if osp.isabs(_name): return _name paths = os.environ.get('PATH', '').split(os.pathsep) eax = find_in_paths(_name, paths) if eax: return eax if required: raise NameError('Could not find %s executable' % name)
def __init__(self, path, mkdir=False, logsuffix=''): if path: pwd = getpwd() self._prev_pwd = pwd else: self._prev_pwd = None return if not isabs(path): path = normpath(opj(pwd, path)) if not os.path.exists(path) and mkdir: self._mkdir = True os.mkdir(path) else: self._mkdir = False lgr.debug("chdir %r -> %r %s", self._prev_pwd, path, logsuffix) os.chdir(path) # for grep people -- ok, to chdir here! os.environ['PWD'] = path
def resolve_output_to_url(self, ctx, target): """Given ``target``, this has to return the url through which the output file can be referenced. ``target`` may be a relative or absolute path, and is usually taking from the :attr:`Bundle.output` property. This is different from :meth:`resolve_source_to_url` in that you do not passed along the result of :meth:`resolve_output_to_path`. This is because in many use cases, the filesystem is not available at the point where the output url is needed (the media server may on a different machine). """ if not path.isabs(target): # If relative, output files are written to env.directory, # thus we can simply base all values off of env.url. return url_prefix_join(ctx.url, target) else: # If an absolute output path was specified, then search # the url mappings. return self.query_url_mapping(ctx, target)
def load_tests_from_directory(dir, ext=None): ext = ext or '.out' if not isabs(dir): dir = join(dirname(__file__), dir) if not isdir(dir): raise RuntimeError('%s does not exist or is not a directory' % dir) for pyfile in sorted(glob(join(dir, '*.py'))): py_code, options = load_python_code(pyfile) if py_code is None: yield pytest.mark.skip((split(pyfile)[1], None, None, None))(reason=options) continue cmpfile = splitext(pyfile)[0] + ext if exists(cmpfile): with open(cmpfile, encoding='utf-8') as f: expected = f.read() # The first item is to make it easier to spot the right test # in verbose mode yield split(pyfile)[1], py_code, options, expected else: raise RuntimeError('%s has no correspondent %s' % (pyfile, cmpfile))
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
def locateProgram(program): """ Locate a program using the PATH environment variable. Return the unchanged program value if it's not possible to get the full program path. """ if isabs(program): return program if dirname(program): # ./test => $PWD/./test # ../python => $PWD/../python program = path_join(getcwd(), program) program = normpath(program) return program paths = getenv('PATH') if not paths: return program for path in paths.split(pathsep): filename = path_join(path, program) if access(filename, X_OK): return filename return program
def normalize_storage_argument(storage): if storage: return (op.join(os.getcwd(), storage) if not op.isabs(storage) else storage) else: return DEFAULT_STORAGE
def run(self): bld = self.generator.bld linked=[] target_paths = [] for g in bld.groups: for tgen in g: # FIXME it might be better to check if there is a link_task (getattr?) target_paths += [tgen.path.get_bld().bldpath()] linked += [t.outputs[0].bldpath() for t in getattr(tgen, 'tasks', []) if t.__class__.__name__ in ['cprogram', 'cshlib', 'cxxprogram', 'cxxshlib']] lib_list = [] if len(linked): cmd = [self.env.LDD] + linked # FIXME add DYLD_LIBRARY_PATH+PATH for osx+win32 ldd_env = {'LD_LIBRARY_PATH': ':'.join(target_paths + self.env.LIBPATH)} # FIXME the with syntax will not work in python 2 with tmpfile() as result: self.exec_command(cmd, env=ldd_env, stdout=result) result.seek(0) for line in result.readlines(): words = line.split() if len(words) < 3 or words[1] != '=>': continue lib = words[2] if lib == 'not': continue if any([lib.startswith(p) for p in [bld.bldnode.abspath(), '('] + self.env.SOFTLINK_EXCLUDE]): continue if not isabs(lib): continue lib_list.append(lib) lib_list = sorted(set(lib_list)) self.outputs[0].write(linesep.join(lib_list + self.env.DYNAMIC_LIBS)) return 0
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)
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)
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
def isabs(self): return isabs(self.path)
def test(): it.assertTrue(p.isabs(it.parser.getTargetDir())) it.assertEqual( it.parser.getTargetDir(), p.abspath(p.join(TEST_CONFIG_PARSER_SUPPORT_PATH, '.build')))
def _getSourcePath(self, path): """ Normalizes and handles absolute/relative paths """ source_path = p.normpath(p.expanduser(path)) # If the path to the source file was not absolute, we assume # it was relative to the config file base path if not p.isabs(source_path): fname_base_dir = p.dirname(p.abspath(self.filename)) source_path = p.join(fname_base_dir, source_path) return source_path
def simpleParse(filename): """ """ assert p.exists(filename), "Filename '%s' doesn't exists" % filename target_dir = None builder_name = None for _line in open(filename, mode='rb').readlines(): line = _replaceCfgComments("", _line.decode(errors='ignore')) for match in re.finditer( r"^\s*target_dir\s*=\s*(?P<target_dir>.+)\s*$" r"|" r"^\s*builder\s*=\s*(?P<builder>.+)\s*$", line): match_dict = match.groupdict() if match_dict['target_dir'] is not None: target_dir = match_dict['target_dir'] if match_dict['builder'] is not None: builder_name = match_dict['builder'] if target_dir: target_dir = p.abspath(p.join(p.dirname(filename), target_dir)) else: target_dir = '.hdlcc' if not p.isabs(target_dir): target_dir = p.join(p.dirname(filename), target_dir) ConfigParser._logger.info("Simple parse found target_dir = %s and " "builder = %s", repr(target_dir), repr(builder_name)) return target_dir, builder_name
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
def _make_absolute(path, prefix): """ Makes 'path' absolute if it isn't already by prefixing 'prefix' """ if not isabs(path): return join(prefix, path) return path
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
def _assert_entries(self, entries): for entry in entries: assert isinstance(entry, BaseIndexEntry) assert not osp.isabs(entry.path) assert "\\" not in entry.path # END for each entry
def _to_relative_path(self, path): """:return: Version of path relative to our git directory or raise ValueError if it is not within our git direcotory""" if not osp.isabs(path): return path if self.repo.bare: raise InvalidGitRepositoryError("require non-bare repository") relative_path = path.replace(self.repo.working_tree_dir + os.sep, "") if relative_path == path: raise ValueError("Absolute path %r is not in git repository at %r" % (path, self.repo.working_tree_dir)) return relative_path
def _entries_for_paths(self, paths, path_rewriter, fprogress, entries): entries_added = list() if path_rewriter: for path in paths: if osp.isabs(path): abspath = path gitrelative_path = path[len(self.repo.working_tree_dir) + 1:] else: gitrelative_path = path abspath = osp.join(self.repo.working_tree_dir, gitrelative_path) # end obtain relative and absolute paths blob = Blob(self.repo, Blob.NULL_BIN_SHA, stat_mode_to_index_mode(os.stat(abspath).st_mode), to_native_path_linux(gitrelative_path)) # TODO: variable undefined entries.append(BaseIndexEntry.from_blob(blob)) # END for each path del(paths[:]) # END rewrite paths # HANDLE PATHS assert len(entries_added) == 0 for filepath in self._iter_expand_paths(paths): entries_added.append(self._store_path(filepath, fprogress)) # END for each filepath # END path handling return entries_added
def _write_feature_to_htk(features, out_dir, file, frame_rate): r""" Writes to output file the arr array with the given frame rate in the HTK binary format """ from struct import pack num_frames, feature_size = np.shape(features) if path.isabs(file): # case of AAM output_filename = file_to_feature(file, extension='.htk') else: # case of DCT output_filename = path.splitext(file)[0] + '.htk' outfile = open(out_dir + output_filename, 'wb') num_samples = np.size(features) sample_period = int(1 / frame_rate * (10 ** 7)) sample_size = feature_size * 4 parameter_kid = 9 # user-defined htk type header = pack( '>IIHH', # big endian, 2 uint, 2 ushort num_samples, sample_period, sample_size, parameter_kid) content = b'' for val in np.nditer(features, op_dtypes=np.float32, casting='same_kind', op_flags=['readonly', 'copy']): content += pack('>f', val) outfile.write(header) outfile.write(content) outfile.close()
def check_options(self): path_options = ( "accesslog", "config", "repo", "errorlog", "pidfile", "sock", "theme", ) for path_option in path_options: value = self.get(path_options, None) if value and not path.isabs(value): self[path_options] = path.abspath(path.expanduser(value))
def load_ui(self, path: str): """Load in .ui file created by Qt Designer.""" if not isabs(path): # If path is relative find ui file relative to file containing QWidgetNodeBase child class. path = join(dirname(inspect.getfile(sys._getframe(1))), path) uic.loadUi(path, self)
def update_symlink(self, name, source, force): """ Load in a plugin by creating a symlink to it. :param name: Plugin name. :param source: Source path. :param bool force: Delete any existing symlink and recreate it. :returns: ``True`` if successful. :rtype: bool """ target_dir = join(self.path, "plugins", name) # Only update if the plugin doesn't exist or is being forced. if not force and isdir(target_dir): return True # If source dir path is relative, get absolute path relative to the project root. if not isabs(source): source = join(self.path, source) # Check if source dir exists. if not isdir(source): return False # Check if source dir is a valid uj project. try: UjProject(source, None) except InvalidUjProjectError: return False rm(target_dir) symlink(relpath(source, join(self.path, "plugins")), target_dir, target_is_directory=True) self.print("created symlink '{}' with source '{}'".format(name, target_dir)) return True # TODO: Implement web, zip and copy plugin source handlers.
def test_uri_normalize_fileuri_abs(): uri = URI('file:///test.xmi') assert path.isabs(uri.normalize())
def load_configs( config_fns, input_cfg_fn, input_root ): ''' This function loads the configuration files of all pages which are part of the project. From the configuration files a 'dirlisttree' instance is generated which mimics the directory structure of the project and which can be accessed conveniently in a jinja template. ''' cfg_tree = dirlisttree() for cfg_fn in config_fns: if path.isabs(cfg_fn): raise ValueError('Error: You cannot use absolute paths here: %s' % cfg_fn) cfg_fn_base, _ = path.splitext( cfg_fn ) _, cfg_name = path.split(cfg_fn_base) html_fn = "/" + cfg_fn_base + ".html" with open(cfg_fn, 'r', encoding='utf-8') as cfg_file: cfg = yaml.load(cfg_file.read()) # Add special attributes: cfg['url'] = html_fn cfg['name'] = cfg_name if 'title' not in cfg: cfg['title'] = cfg_name # Configuration of current page gets special attention: if cfg_fn == input_cfg_fn: config = cfg pure_fn, _ = path.split( cfg_fn ) cfg_tree[pure_fn].append(cfg) return cfg_tree, config
def normrelpath(base, target): """ This function takes the base and target arguments as paths, and returns an equivalent relative path from base to the target, if both provided paths are absolute. """ if not all(map(isabs, [base, target])): return target return relpath(normpath(target), dirname(normpath(base)))
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)
def test_compiled_filenames(pyi_builder): pyi_builder.test_source(""" import pyi_dummy_module from os.path import isabs assert not isabs(pyi_dummy_module.dummy.__code__.co_filename), "pyi_dummy_module.dummy.__code__.co_filename has compiled filename: %s" % (pyi_dummy_module.dummy.__code__.co_filename,) assert not isabs(pyi_dummy_module.DummyClass.dummyMethod.__code__.co_filename), "pyi_dummy_module.DummyClass.dummyMethod.__code__.co_filename has compiled filename: %s" % (pyi_dummy_module.DummyClass.dummyMethod.__code__.co_filename,) """)
def _set_certificate(self, server_certificate_path): """ Set certificate to use for ScaleIO REST gateway calls :return: Nothing """ from os.path import isabs if isabs(server_certificate_path): self.verify_cert = True self.cert_path = server_certificate_path