我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.altsep()。
def load_local_url(self, url): match = self.local_url_re.match(urlparse.urlsplit(url).path) rest = match.group('rest') for sep in os.sep, os.altsep: if sep and sep != '/': rest.replace(sep, '/') path = openerp.modules.get_module_resource( match.group('module'), 'static', *(rest.split('/'))) if not path: return None try: with open(path, 'rb') as f: # force complete image load to ensure it's valid image data image = I.open(f) image.load() f.seek(0) return f.read().encode('base64') except Exception: logger.exception("Failed to load local image %r", url) return None
def pickaddr(self, proto): if proto == socket.AF_INET: return (HOST, 0) else: # XXX: We need a way to tell AF_UNIX to pick its own name # like AF_INET provides port==0. dir = None if os.name == 'os2': dir = '\socket' fn = tempfile.mktemp(prefix='unix_socket.', dir=dir) if os.name == 'os2': # AF_UNIX socket names on OS/2 require a specific prefix # which can't include a drive letter and must also use # backslashes as directory separators if fn[1] == ':': fn = fn[2:] if fn[0] in (os.sep, os.altsep): fn = fn[1:] if os.sep == '/': fn = fn.replace(os.sep, os.altsep) else: fn = fn.replace(os.altsep, os.sep) self.test_files.append(fn) return fn
def from_file(cls, filename): st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) arcname = os.path.normpath(os.path.splitdrive(filename)[1])[-16:] while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] if isdir: raise RuntimeError('WadFile expects a file, got a directory') info = cls(arcname) info.type = TYPE_LUMP info.file_size = st.st_size info.disk_size = st.st_size info.filename = os.path.basename(arcname)[-16:] return info
def make_relative(self, path): npath, last = os.path.split(normalize_path(path)) baselen = len(self.basedir) parts = [last] sep = os.altsep == '/' and '/' or os.sep while len(npath) >= baselen: if npath == self.basedir: parts.append(os.curdir) parts.reverse() return sep.join(parts) npath, last = os.path.split(npath) parts.append(last) else: return path
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. # Strip trailing path separator, unless it represents the root. if (targetpath[-1:] in (os.path.sep, os.path.altsep) and len(os.path.splitdrive(targetpath)[1]) > 1): targetpath = targetpath[:-1] # don't include leading "/" from file name if present if member.filename[0] == '/': targetpath = os.path.join(targetpath, member.filename[1:]) else: targetpath = os.path.join(targetpath, member.filename) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.filename[-1] == '/': if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath source = self.open(member, pwd=pwd) target = file(targetpath, "wb") shutil.copyfileobj(source, target) source.close() target.close() return targetpath
def fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. comparepath = os.path.normcase(path) longest = "" for dir in sys.path: dir = os.path.normcase(dir) if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep: if len(dir) > len(longest): longest = dir if longest: base = path[len(longest) + 1:] else: base = path # the drive letter is never part of the module name drive, base = os.path.splitdrive(base) base = base.replace(os.sep, ".") if os.altsep: base = base.replace(os.altsep, ".") filename, ext = os.path.splitext(base) return filename.lstrip(".")
def get_template(self, uri): """Return a :class:`.Template` object corresponding to the given ``uri``. .. note:: The ``relativeto`` argument is not supported here at the moment. """ try: if self.filesystem_checks: return self._check(uri, self._collection[uri]) else: return self._collection[uri] except KeyError: u = re.sub(r'^\/+', '', uri) for dir in self.directories: # make sure the path seperators are posix - os.altsep is empty # on POSIX and cannot be used. dir = dir.replace(os.path.sep, posixpath.sep) srcfile = posixpath.normpath(posixpath.join(dir, u)) if os.path.isfile(srcfile): return self._load(srcfile, uri) else: raise exceptions.TopLevelLookupException( "Cant locate template for uri %r" % uri)
def make_relative(self,path): npath, last = os.path.split(normalize_path(path)) baselen = len(self.basedir) parts = [last] sep = os.altsep=='/' and '/' or os.sep while len(npath)>=baselen: if npath==self.basedir: parts.append(os.curdir) parts.reverse() return sep.join(parts) npath, last = os.path.split(npath) parts.append(last) else: return path
def __nullpathconv(path): return path.replace(os.altsep, os.sep)
def __unixpathconv(path): # two known drive letter variations: "x;" and "$x" if path[0] == '$': conv = path[1] + ':' + path[2:] elif path[1] == ';': conv = path[0] + ':' + path[2:] else: conv = path return conv.replace(os.altsep, os.sep) # decide what field separator we can try to use - Unix standard, with # the platform's path separator as an option. No special field conversion # handler is required when using the platform's path separator as field # separator, but are required for the home directory and shell fields when # using the standard Unix (":") field separator.
def test_altsep_and_sep_cache_from_source(self): # Windows path and PEP 3147 where altsep is right of sep. self.assertEqual( imp.cache_from_source('\\foo\\bar/baz\\qux.py', True), '\\foo\\bar/baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
def test_sep_altsep_and_sep_cache_from_source(self): # Windows path and PEP 3147 where sep is right of altsep. self.assertEqual( imp.cache_from_source('\\foo\\bar\\baz/qux.py', True), '\\foo\\bar\\baz/__pycache__/qux.{}.pyc'.format(self.tag))
def test_write_pyfile(self): with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp: fn = __file__ if fn.endswith('.pyc') or fn.endswith('.pyo'): path_split = fn.split(os.sep) if os.altsep is not None: path_split.extend(fn.split(os.altsep)) if '__pycache__' in path_split: fn = imp.source_from_cache(fn) else: fn = fn[:-1] zipfp.writepy(fn) bn = os.path.basename(fn) self.assertNotIn(bn, zipfp.namelist()) self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist()) with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp: fn = __file__ if fn.endswith(('.pyc', '.pyo')): fn = fn[:-1] zipfp.writepy(fn, "testpackage") bn = "%s/%s" % ("testpackage", os.path.basename(fn)) self.assertNotIn(bn, zipfp.namelist()) self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. # Strip trailing path separator, unless it represents the root. if (targetpath[-1:] in (os.path.sep, os.path.altsep) and len(os.path.splitdrive(targetpath)[1]) > 1): targetpath = targetpath[:-1] # don't include leading "/" from file name if present if member.filename[0] == '/': targetpath = os.path.join(targetpath, member.filename[1:]) else: targetpath = os.path.join(targetpath, member.filename) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.filename[-1] == '/': if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath source = self.open(member, pwd=pwd) target = open(targetpath, "wb") shutil.copyfileobj(source, target) source.close() target.close() return targetpath
def _fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. comparepath = os.path.normcase(path) longest = "" for dir in sys.path: dir = os.path.normcase(dir) if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep: if len(dir) > len(longest): longest = dir if longest: base = path[len(longest) + 1:] else: base = path # the drive letter is never part of the module name drive, base = os.path.splitdrive(base) base = base.replace(os.sep, ".") if os.altsep: base = base.replace(os.altsep, ".") filename, ext = os.path.splitext(base) return filename.lstrip(".")