我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.split()。
def _index(self): try: return self._dirindex except AttributeError: ind = {} for path in self.zipinfo: parts = path.split(os.sep) while parts: parent = os.sep.join(parts[:-1]) if parent in ind: ind[parent].append(parts[-1]) break else: ind[parent] = [parts.pop()] self._dirindex = ind return ind
def _by_version_descending(names): """ Given a list of filenames, return them in descending order by version number. >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg' >>> _by_version_descending(names) ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg'] >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg' >>> _by_version_descending(names) ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg'] """ def _by_version(name): """ Parse each component of the filename """ name, ext = os.path.splitext(name) parts = itertools.chain(name.split('-'), [ext]) return [packaging.version.parse(part) for part in parts] return sorted(names, key=_by_version, reverse=True)
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist)
def _dep_map(self): try: return self.__dep_map except AttributeError: dm = self.__dep_map = {None: []} for name in 'requires.txt', 'depends.txt': for extra, reqs in split_sections(self._get_metadata(name)): if extra: if ':' in extra: extra, marker = extra.split(':', 1) if invalid_marker(marker): # XXX warn reqs = [] elif not evaluate_marker(marker): reqs = [] extra = safe_extra(extra) or None dm.setdefault(extra, []).extend(parse_requirements(reqs)) return dm
def run_script(self, script_name, namespace): script = 'scripts/' + script_name if not self.has_metadata(script): raise ResolutionError("No script named %r" % script_name) script_text = self.get_metadata(script).replace('\r\n', '\n') script_text = script_text.replace('\r', '\n') script_filename = self._fn(self.egg_info, script) namespace['__file__'] = script_filename if os.path.exists(script_filename): source = open(script_filename).read() code = compile(source, script_filename, 'exec') exec(code, namespace, namespace) else: from linecache import cache cache[script_filename] = ( len(script_text), 0, script_text.split('\n'), script_filename ) script_code = compile(script_text, script_filename, 'exec') exec(script_code, namespace, namespace)
def record(self): "Begin screen grab recording" if self.recFolder is None: fldr = TkDialog(FOLDER, initialdir="./").run() if fldr: self.recFolder = fldr else: return try: param = TkDialog(str, "Enter recording " + "parameters using one of these formats:\n" + "fps\nfps w h\nfps x y w h", "Record", initialvalue="15").run() param = [int(c) for c in param.split(" ") if c] self.frameRate = param[0] self.grab = Grabber(param[1:] if len(param) > 1 else None) self.rec = [] vid = self.vid if vid is not None: self.vid = None self -= vid self._recordStart = time() except: pass # Abort!
def parse(fn): """Parse a file name into a pattern; for example... 'img007.png' --> ('img{:03d}.png', 7)""" path, fn = split(fn) if not path: path = "." ftype = fn.split(".")[-1] fn = fn[:-1-len(ftype)] n = None i = 0 for c in fn: if c in "0123456789": n = i break else: i += 1 if n is None: return None start = int(fn[n:]) if fn[n] == "0": d = len(fn) - n fn = fn[:n] + "{:0" + str(d) + "d}." + ftype else: fn = fn[:n] + "{}." + ftype return path + "/" + fn, start
def detect_protocol_from_name(self, path): pattern = "\d{4}(\d+|\D)\D" codes = { 'r':'sparsenoise', 'o':'movingbar', 'f':'flashbar', 'm':'multistim' # here just for assertion } filename = path.split(path)[1] match = re.search(pattern, path) if hasattr(match, 'end') : code = codes.get(path[match.end() - 1].lower(), None) assert code != 'm', "multistim file detected" return code elif 'spt' in filename.lower() : return 'spontaneousactivity' else : return None
def _macosx_vers(_cache=[]): if not _cache: import platform version = platform.mac_ver()[0] # fallback for MacPorts if version == '': import plistlib plist = '/System/Library/CoreServices/SystemVersion.plist' if os.path.exists(plist): if hasattr(plistlib, 'readPlist'): plist_content = plistlib.readPlist(plist) if 'ProductVersion' in plist_content: version = plist_content['ProductVersion'] _cache.append(version.split('.')) return _cache[0]
def run_script(self,script_name,namespace): script = 'scripts/'+script_name if not self.has_metadata(script): raise ResolutionError("No script named %r" % script_name) script_text = self.get_metadata(script).replace('\r\n','\n') script_text = script_text.replace('\r','\n') script_filename = self._fn(self.egg_info,script) namespace['__file__'] = script_filename if os.path.exists(script_filename): execfile(script_filename, namespace, namespace) else: from linecache import cache cache[script_filename] = ( len(script_text), 0, script_text.split('\n'), script_filename ) script_code = compile(script_text,script_filename,'exec') exec(script_code, namespace, namespace)
def _dep_map(self): try: return self.__dep_map except AttributeError: dm = self.__dep_map = {None: []} for name in 'requires.txt', 'depends.txt': for extra,reqs in split_sections(self._get_metadata(name)): if extra: if ':' in extra: extra, marker = extra.split(':',1) if invalid_marker(marker): reqs=[] # XXX warn elif not evaluate_marker(marker): reqs=[] extra = safe_extra(extra) or None dm.setdefault(extra,[]).extend(parse_requirements(reqs)) return dm
def which_file(fname): """prints paths for fname where fname can be found, in case of .dll loads it""" files = [] path = win32api.GetEnvironmentVariable('PATH') # try paths as described in MSDN dirs = [os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory()] + path.split(';') dirs_norm = [] dirs_l = [] for d in dirs: dn = d.lower() if dn not in dirs_l: dirs_l.append(dn) dirs_norm.append(d) for d in dirs_norm: fname2 = os.path.join(d, fname) if os.path.exists(fname2): if fname2 not in files: files.append(fname2) if files: print('\n'.join([get_file_info(f) for f in files])) h = 0 if fname.lower().endswith('.dll'): print('\ttrying to load "%s" ...' % (fname)) try: h = win32api.LoadLibrary(fname) if h: dll_name = win32api.GetModuleFileName(h) print('\t%s loaded' % (dll_name)) except: print('\tCannot load "%s" !!!' % (fname))
def handle_show(self): if self.isalive(): sfile_bufnr = self.vimx.buffer_add(self.get_confpath()) self.vimx.command('exe "tab drop ".escape(bufname({0}), "$%# ")' .format(sfile_bufnr)) json_str = json.dumps(self.state, indent=4, separators=(',', ': ')) def json_show(b): if b.number == sfile_bufnr: b[:] = json_str.split('\n') raise StopIteration self.vimx.map_buffers(json_show) if self.help_flags["new"] and self.help_flags["session_show"]: self.vimx.log( 'Save this file, and do `:GGsession reload` to load any changes made.') self.help_flags["session_show"] = False else: self.vimx.log("No active session.")
def run_script(self, script_name, namespace): script = 'scripts/'+script_name if not self.has_metadata(script): raise ResolutionError("No script named %r" % script_name) script_text = self.get_metadata(script).replace('\r\n', '\n') script_text = script_text.replace('\r', '\n') script_filename = self._fn(self.egg_info, script) namespace['__file__'] = script_filename if os.path.exists(script_filename): source = open(script_filename).read() code = compile(source, script_filename, 'exec') exec(code, namespace, namespace) else: from linecache import cache cache[script_filename] = ( len(script_text), 0, script_text.split('\n'), script_filename ) script_code = compile(script_text, script_filename,'exec') exec(script_code, namespace, namespace)
def _rebuild_mod_path(orig_path, package_name, module): """ Rebuild module.__path__ ensuring that all entries are ordered corresponding to their sys.path order """ sys_path = [_normalize_cached(p) for p in sys.path] def position_in_sys_path(path): """ Return the ordinal of the path based on its position in sys.path """ path_parts = path.split(os.sep) module_parts = package_name.count('.') + 1 parts = path_parts[:-module_parts] return sys_path.index(_normalize_cached(os.sep.join(parts))) orig_path.sort(key=position_in_sys_path) module.__path__[:] = [_normalize_cached(p) for p in orig_path]
def _dep_map(self): try: return self.__dep_map except AttributeError: dm = self.__dep_map = {None: []} for name in 'requires.txt', 'depends.txt': for extra, reqs in split_sections(self._get_metadata(name)): if extra: if ':' in extra: extra, marker = extra.split(':', 1) if invalid_marker(marker): # XXX warn reqs=[] elif not evaluate_marker(marker): reqs=[] extra = safe_extra(extra) or None dm.setdefault(extra,[]).extend(parse_requirements(reqs)) return dm