我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用posixpath.dirname()。
def test_realpath_symlink_loops(self): # Bug #930024, return the path unchanged if we get into an infinite # symlink loop. try: old_path = abspath('.') os.symlink(ABSTFN, ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN) os.symlink(ABSTFN+"1", ABSTFN+"2") os.symlink(ABSTFN+"2", ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1") self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2") # Test using relative path as well. os.chdir(dirname(ABSTFN)) self.assertEqual(realpath(basename(ABSTFN)), ABSTFN) finally: os.chdir(old_path) support.unlink(ABSTFN) support.unlink(ABSTFN+"1") support.unlink(ABSTFN+"2")
def resolveEntity(self, publicId, systemId): assert systemId is not None source = DOMInputSource() source.publicId = publicId source.systemId = systemId source.byteStream = self._get_opener().open(systemId) # determine the encoding if the transport provided it source.encoding = self._guess_media_encoding(source) # determine the base URI is we can import posixpath, urlparse parts = urlparse.urlparse(systemId) scheme, netloc, path, params, query, fragment = parts # XXX should we check the scheme here as well? if path and not path.endswith("/"): path = posixpath.dirname(path) + "/" parts = scheme, netloc, path, params, query, fragment source.baseURI = urlparse.urlunparse(parts) return source
def show_search_results(abe, page, found): if not found: page['body'] = [ '<p>No results found.</p>\n', abe.search_form(page)] return if len(found) == 1: # Undo shift_path_info. sn = posixpath.dirname(page['env']['SCRIPT_NAME']) if sn == '/': sn = '' page['env']['SCRIPT_NAME'] = sn page['env']['PATH_INFO'] = '/' + page['dotdot'] + found[0]['uri'] del(page['env']['QUERY_STRING']) raise Redirect() body = page['body'] body += ['<h3>Search Results</h3>\n<ul>\n'] for result in found: body += [ '<li><a href="', page['dotdot'], escape(result['uri']), '">', escape(result['name']), '</a></li>\n'] body += ['</ul>\n']
def adjust_uri(self, uri, relativeto): """Adjust the given ``uri`` based on the given relative URI.""" key = (uri, relativeto) if key in self._uri_cache: return self._uri_cache[key] if uri[0] != '/': if relativeto is not None: v = self._uri_cache[key] = posixpath.join( posixpath.dirname(relativeto), uri) else: v = self._uri_cache[key] = '/' + uri else: v = self._uri_cache[key] = uri return v
def test_realpath_resolve_first(self): # Bug #1213894: The first component of the path, if not absolute, # must be resolved too. try: old_path = abspath('.') os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.symlink(ABSTFN, ABSTFN + "link") os.chdir(dirname(ABSTFN)) base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k") finally: os.chdir(old_path) support.unlink(ABSTFN + "link") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def __init__(self, gyp_path, path, build_file_dict): self.gyp_path = gyp_path self.path = path self.project = gyp.xcodeproj_file.PBXProject(path=path) projectDirPath = gyp.common.RelativePath( os.path.dirname(os.path.abspath(self.gyp_path)), os.path.dirname(path) or '.') self.project.SetProperty('projectDirPath', projectDirPath) self.project_file = \ gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project}) self.build_file_dict = build_file_dict # TODO(mark): add destructor that cleans up self.path if created_dir is # True and things didn't complete successfully. Or do something even # better with "try"? self.created_dir = False try: os.makedirs(self.path) self.created_dir = True except OSError, e: if e.errno != errno.EEXIST: raise
def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: test_support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def dirlist(self, path, sep=True, hidden=False, dirsonly=False, r=True): # get remote path if not in recursive mode if r: path = self.rpath(path) # receive list of files on remote device str_recv = self.cmd('@PJL FSDIRLIST NAME="' + path + '" ENTRY=1 COUNT=65535') list = {} for item in str_recv.splitlines(): # get directories dirname = re.findall("^(.*)\s+TYPE\s*=\s*DIR$", item) if dirname and (dirname[0] not in ("", ".", "..") or hidden): sep = c.SEP if sep and dirname[0][-1:] != c.SEP else '' list[dirname[0] + sep] = None # get files filename = re.findall("^(.*)\s+TYPE\s*=\s*FILE", item) filesize = re.findall("FILE\s+SIZE\s*=\s*(\d*)", item) if filename and filesize and not dirsonly: list[filename[0]] = filesize[0] return list # ------------------------[ ls <path> ]-------------------------------
def resolveEntity(self, publicId, systemId): assert systemId is not None source = DOMInputSource() source.publicId = publicId source.systemId = systemId source.byteStream = self._get_opener().open(systemId) # determine the encoding if the transport provided it source.encoding = self._guess_media_encoding(source) # determine the base URI is we can import posixpath, urllib.parse parts = urllib.parse.urlparse(systemId) scheme, netloc, path, params, query, fragment = parts # XXX should we check the scheme here as well? if path and not path.endswith("/"): path = posixpath.dirname(path) + "/" parts = scheme, netloc, path, params, query, fragment source.baseURI = urllib.parse.urlunparse(parts) return source
def get_dependents(archive, filename): """ Normalise dependency file paths to absolute ones Relative paths are relative to parent object """ src = archive.read(filename) node = fromstring(src) rels = RelationshipList.from_tree(node) folder = posixpath.dirname(filename) parent = posixpath.split(folder)[0] for r in rels.Relationship: if r.TargetMode == "External": continue elif r.target.startswith("/"): r.target = r.target[1:] else: pth = posixpath.join(parent, r.target) r.target = posixpath.normpath(pth) return rels
def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def _walk_namespace_hierarchy(namespace): assert namespace.startswith("/") yield namespace while namespace != "/": namespace = posixpath.dirname(namespace) yield namespace
def short_link(abe, page, link): base = abe.base_url if base is None: env = page['env'].copy() env['SCRIPT_NAME'] = posixpath.normpath( posixpath.dirname(env['SCRIPT_NAME'] + env['PATH_INFO']) + '/' + page['dotdot']) env['PATH_INFO'] = link full = wsgiref.util.request_uri(env) else: full = base + link return ['<p class="shortlink">Short Link: <a href="', page['dotdot'], link, '">', full, '</a></p>\n']
def list_policies(): import pkgutil import Chain policies = [] for _, name, ispkg in pkgutil.iter_modules(path=[os.path.dirname(Chain.__file__)]): if not ispkg: policies.append(name) return policies
def autohandler(template, context, name='autohandler'): lookup = context.lookup _template_uri = template.module._template_uri if not lookup.filesystem_checks: try: return lookup._uri_cache[(autohandler, _template_uri, name)] except KeyError: pass tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name] while len(tokens): path = '/' + '/'.join(tokens) if path != _template_uri and _file_exists(lookup, path): if not lookup.filesystem_checks: return lookup._uri_cache.setdefault( (autohandler, _template_uri, name), path) else: return path if len(tokens) == 1: break tokens[-2:] = [name] if not lookup.filesystem_checks: return lookup._uri_cache.setdefault( (autohandler, _template_uri, name), None) else: return None
def resolve_path(self, name, parent_path=None): if parent_path and not parent_path.startswith("<") and \ not parent_path.startswith("/") and \ not name.startswith("/"): current_path = os.path.join(self.root, parent_path) file_dir = os.path.dirname(os.path.abspath(current_path)) relative_path = os.path.abspath(os.path.join(file_dir, name)) if relative_path.startswith(self.root): name = relative_path[len(self.root) + 1:] return name
def resolve_path(self, name, parent_path=None): if parent_path and not parent_path.startswith("<") and \ not parent_path.startswith("/") and \ not name.startswith("/"): file_dir = posixpath.dirname(parent_path) name = posixpath.normpath(posixpath.join(file_dir, name)) return name
def mkdir_slashfix_open(filename, mode): """Like common.slashfix_open(), but make directories as needed.""" real_filename = common.slashfix(filename) directory = os.path.dirname(real_filename) os.makedirs(directory, exist_ok=True) return open(real_filename, mode)