我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.replace()。
def map(self, path): """Map `path` through the aliases. `path` is checked against all of the patterns. The first pattern to match is used to replace the root of the path with the result root. Only one pattern is ever used. If no patterns match, `path` is returned unchanged. The separator style in the result is made to match that of the result in the alias. """ for regex, result, pattern_sep, result_sep in self.aliases: m = regex.match(path) if m: new = path.replace(m.group(0), result) if pattern_sep != result_sep: new = new.replace(pattern_sep, result_sep) if self.locator: new = self.locator.canonical_filename(new) return new return path
def extract_docker_layer(img: tarfile.TarFile, layer_id: str, extract_path: str): with tarfile.open(fileobj=img.extractfile('%s/layer.tar' % layer_id), errorlevel=0, dereference=True) as layer: layer.extractall(path=extract_path) log.debug('processing whiteouts') for member in layer.getmembers(): path = member.path if path.startswith('.wh.') or '/.wh.' in path: if path.startswith('.wh.'): newpath = path[4:] else: newpath = path.replace('/.wh.', '/') try: log.debug('removing path %s', newpath) os.unlink(path) os.unlink(newpath) except OSError as err: if err.errno != errno.ENOENT: raise
def process_redirect_file(app, path, ent): parent_path = path.replace(app.builder.srcdir, app.builder.outdir) with open(os.path.join(path, ent)) as redirects: for line in redirects.readlines(): from_path, to_path = line.rstrip().split(' ') from_path = from_path.replace('.rst', '.html') to_path = to_path.replace('.rst', '.html') redirected_filename = os.path.join(parent_path, from_path) redirected_directory = os.path.dirname(redirected_filename) if not os.path.exists(redirected_directory): os.makedirs(redirected_directory) with open(redirected_filename, 'w') as f: f.write('<html><head><meta http-equiv="refresh" content="0; ' 'url=%s" /></head></html>' % to_path)
def get_src_path(obj, src_root='tefla', append_base=True): """Creates a src path string with line info for use as markdown link. """ path = getsourcefile(obj) if not src_root in path: # this can happen with e.g. # inlinefunc-wrapped functions if hasattr(obj, "__module__"): path = "%s.%s" % (obj.__module__, obj.__name__) else: path = obj.__name__ path = path.replace(".", "/") try: pre, post = path.rsplit(src_root + "/", 1) except: pre, post = '', '' lineno = get_line_no(obj) lineno = "" if lineno is None else "#L{}".format(lineno) path = src_root + "/" + post + lineno if append_base: path = os.path.join( 'https://github.com/openagi/tefla/blob/master', path) return path
def directory_name(release): ''' Returns the proper directory name for a Release. ''' artist = textwrap.shorten(release.album_artist, width=50, placeholder='_') album = textwrap.shorten(release.title, width=40, placeholder='_') year = release.year if release.bitrate == 'V0 (VBR)': format_info = 'V0' elif release.bitrate == '320': format_info = '320' else: format_info = release.format if release.medium != 'CD': format_info = release.medium + ' ' + format_info path = ALBUM_TEMPLATE.substitute(**locals()) if release.catalog_number: path += ' {' + release.catalog_number + '}' path = path.replace('/', '_').replace('\\', '_') path = sanitize_path(path) return path
def test_all_table_entries(harness, files, request_uri, expected): # set up the specified files realfiles = tuple([ f if f.endswith('/') else (f, GENERIC_SPT) for f in files ]) harness.fs.www.mk(*realfiles) try: state = harness._hit('GET', request_uri, want='state', return_after='dispatch_path_to_filesystem') except exceptions.NotFound: result = '404' except exceptions.Redirect as err: result = '302 ' + err.message else: result = '200' path = format_result(**state) if os.sep != posixpath.sep: path = path.replace(os.sep, posixpath.sep) path = path[len(harness.fs.www.root)+1:] if path: result += " " + path if expected.endswith("*"): expected = expected[:-1] assert result == expected, "Requesting %r, got %r instead of %r" % (request_uri, result, expected)
def fake_init(self, tasker, auth_builder, reporting_channel, client): self.username = 'testing-bot' self.tasker = tasker self.auth_builder = auth_builder self.reporting_channel = reporting_channel self._last_task_poll = datetime.min.replace(tzinfo=pytz.utc) self._last_report = datetime.min.replace(tzinfo=pytz.utc) self.chat = client self.users = {} self.users_by_name = {} self.active_users = {} self.commands = {} self.messages = {}
def shufflePlaylist(self): global epnArrList,site if site == "Local" or site =="Video" or site == "Music" or site == "PlayLists" or epnArrList: t = epnArrList[0] if ' ' in t: print ("++++++++++++++++") m = random.sample(epnArrList,len(epnArrList)) epnArrList[:]=[] epnArrList=m self.list2.clear() for i in epnArrList: i = i.replace('\n','') if ' ' in i: i = i.split(' ')[0] if '#' in i: i = '#'+i self.list2.item(i).setFont(QtGui.QFont('SansSerif', 10,italic=True)) else: self.list2.addItem((i))
def map(self, path): """Map `path` through the aliases. `path` is checked against all of the patterns. The first pattern to match is used to replace the root of the path with the result root. Only one pattern is ever used. If no patterns match, `path` is returned unchanged. The separator style in the result is made to match that of the result in the alias. Returns the mapped path. If a mapping has happened, this is a canonical path. If no mapping has happened, it is the original value of `path` unchanged. """ for regex, result, pattern_sep, result_sep in self.aliases: m = regex.match(path) if m: new = path.replace(m.group(0), result) if pattern_sep != result_sep: new = new.replace(pattern_sep, result_sep) new = canonical_filename(new) return new return path
def build_context_menu(self, pos, view, model, add_menu_label=None): ''' ?????????????????????????????????? :param pos: ?????????????? :param view: ????????? :param model: ????????? :return: ''' # ??????? menu = QtWidgets.QMenu(view) menu_labels = ['Show in Explorer'] if add_menu_label is not None: menu_labels.extend(add_menu_label) actionlist = [] for label in menu_labels: actionlist.append(menu.addAction(label)) action = menu.exec_(view.mapToGlobal(pos)) #menu.close() # -----???? if action is None: return None text = action.text() # Show in Explorer if text == menu_labels[0]: path = self.get_view_select(view, model) # ????????? path = path.encode('cp932') if os.path.isdir(path): subprocess.Popen(r'explorer {0}'.format(path.replace('/', '\\'))) else: subprocess.Popen(r'explorer /select,{0}'.format(path.replace('/', '\\'))) return None return text # ----------------------- # callback # -----------------------
def __init__(self, path, env=_auto_env, secret=False, processor=V.raw): self.path = path self.arg = path.replace(':', '_') env = env or [] if env == self._auto_env: env = [self.arg.upper(), self.path.upper().replace(':', '')] self.env = env if isinstance(self.env, string_types): self.env = [self.env] self.processor = processor if isinstance(secret, string_types): secret = re.compile(secret) self.secret = secret
def latexEscape(text): text = escapingRE.sub(_escapeMatch, text) return text.replace('\n', ' ')
def realpath(path): # Normalise path cwd = os.getcwd() path = os.path.normpath(os.path.join(cwd, path)) if path.startswith(cwd + '/'): path = path[len(cwd)+1:] return path.replace('\\', '/') # windows slashes make LaTeX blow up
def writeNodeData(self, node): buf = StringIO() getLatexText(node, buf.write, latexEscape) self.writer(buf.getvalue().replace('<', '$<$').replace('>', '$>$'))
def visitNode_code(self, node): fout = StringIO() getLatexText(node, fout.write, latexEscape) data = lowerUpperRE.sub(r'\1\\linebreak[1]\2', fout.getvalue()) data = data[:1] + data[1:].replace('.', '.\\linebreak[1]') self.writer('\\texttt{'+data+'}')
def convert_dia(self, src, target): # EVIL DISGUSTING HACK data = os.popen("gunzip -dc %s" % (src)).read() pre = '<dia:attribute name="scaling">\n <dia:real val="1"/>' post = '<dia:attribute name="scaling">\n <dia:real val="0.5"/>' open('%s_hacked.dia' % (src), 'wb').write(data.replace(pre, post)) os.system('gzip %s_hacked.dia' % (src,)) os.system('mv %s_hacked.dia.gz %s_hacked.dia' % (src,src)) # Let's pretend we never saw that. # Silly dia needs an X server, even though it doesn't display anything. # If this is a problem for you, try using Xvfb. os.system("dia %s_hacked.dia -n -e %s" % (src, target))
def create_checkpoint_file(path): # rewrite path path = path.replace('Users', 'home') f = open('{}/checkpoint'.format(config.GENERATED_DIR), 'w') f.write('model_checkpoint_path: "{}"\n'.format(path)) f.write('all_model_checkpoint_paths: "{}"\n'.format(path)) f.close()
def add(self, pattern, result): """Add the `pattern`/`result` pair to the list of aliases. `pattern` is an `fnmatch`-style pattern. `result` is a simple string. When mapping paths, if a path starts with a match against `pattern`, then that match is replaced with `result`. This models isomorphic source trees being rooted at different places on two different machines. `pattern` can't end with a wildcard component, since that would match an entire tree, and not just its root. """ # The pattern can't end with a wildcard component. pattern = pattern.rstrip(r"\/") if pattern.endswith("*"): raise CoverageException("Pattern must not end with wildcards.") pattern_sep = sep(pattern) # The pattern is meant to match a filepath. Let's make it absolute # unless it already is, or is meant to match any prefix. if not pattern.startswith('*') and not isabs_anywhere(pattern): pattern = abs_file(pattern) pattern += pattern_sep # Make a regex from the pattern. fnmatch always adds a \Z or $ to # match the whole string, which we don't want. regex_pat = fnmatch.translate(pattern).replace(r'\Z(', '(') if regex_pat.endswith("$"): regex_pat = regex_pat[:-1] # We want */a/b.py to match on Windows too, so change slash to match # either separator. regex_pat = regex_pat.replace(r"\/", r"[\\/]") # We want case-insensitive matching, so add that flag. regex = re.compile(r"(?i)" + regex_pat) # Normalize the result: it must end with a path separator. result_sep = sep(result) result = result.rstrip(r"\/") + result_sep self.aliases.append((regex, result, pattern_sep, result_sep))
def make_post(session, obj='', csrf='', command='', params = None): """ invokes standart cloud post operation tested operations: ('file/add', 'folder/add', 'file/remove') does not replace existent objects, but logs them """ assert obj is not None, 'no object' assert csrf is not None, 'no CSRF' assert command is not None, 'no command' url = urljoin(CLOUD_URL, command) # api (implemented), email, x-email, x-page-id, build - optional parameters postdata = {'home': obj, 'conflict': CLOUD_CONFLICT, 'token': csrf, 'api': API_VER} if params: assert isinstance(params, dict), 'additional parameters not in dictionary' postdata.update(params) try: r = session.post(url, data=postdata, headers={'Content-Type': 'application/x-www-form-urlencoded'}, verify=VERIFY_SSL) except Exception as e: if LOGGER: LOGGER.error('Make post ({}) HTTP request error: {}'.format(command, e)) return None if r.status_code == requests.codes.ok: return True elif r.status_code == requests.codes.bad: try: r_error = r.json()['body']['home']['error'] except KeyError: r_error = None if r_error == 'exists': if LOGGER: LOGGER.warning('Command {} failed. Object {} already exists'.format(command, obj)) return True if LOGGER: LOGGER.error('Command {} on object {} failed. HTTP code: {}, msg: {}'.format(command, obj, r.status_code, r.text)) return None
def create_cloud_path(path, cloud_base=CLOUD_PATH, local_base=UPLOAD_PATH): """ converts os path to the format acceptable by the cloud example: cloud_base='/backups' local_base='./upload' path='./upload\\level1_1' result='/backups/level1_1' """ normalized_path = path.replace('\\', '/') clean_path = normalized_path.replace(local_base, '', 1) return cloud_base + clean_path
def resolve_text_var_from_metadata_vars(text: str, image_metadata: dict) -> str: if "$" not in text: return text # Extract var name REGEX_EXTRACT_ENV_VAR = re.compile(r'''(\$[{]*[\w]+[}]*)''') REGEX_EXTRACT_ENV_VAR_NAME = re.compile(r'''(\$[{]*)([\w]+)([}]*)''') var_name_mark = REGEX_EXTRACT_ENV_VAR.search(text).group(1) var_name = REGEX_EXTRACT_ENV_VAR_NAME.search(var_name_mark).group(2) # Get image metadata vars image_metadata_environ = set() image_metadata_environ.update(image_metadata["config"]["Env"]) image_metadata_environ.update(image_metadata["container_config"]["Env"]) # Search in environment vars for env in image_metadata_environ: env_name, env_value = env.split("=", maxsplit=1) if var_name in env_name: text = text.replace(var_name_mark, env_value) break return text
def get_entry_point_from_image_metadata(image_metadata: dict) -> str: # Build the launching command entrypoint = image_metadata["config"]["Entrypoint"] if type(entrypoint) is list: entrypoint = " ".join(entrypoint) # Locate the entry-point cmd = image_metadata["config"]["Cmd"] if type(cmd) is list: cmd = " ".join(cmd) if entrypoint and cmd: start_point = "{} {}".format(entrypoint, cmd) elif entrypoint and not cmd: start_point = entrypoint elif not entrypoint and cmd: start_point = cmd else: start_point = "" raw_start_point = start_point.strip() # replace environment vars, like ${HOME} in entry point return resolve_text_var_from_metadata_vars(raw_start_point, image_metadata)
def os9PathConvert(path): """Attempt to convert a unix style path to a Mac OS9 style path. No support for relative paths! """ if path.find("/Volumes") == 0: # it's on the volumes list, some sort of external volume path = path[len("/Volumes")+1:] elif path[0] == "/": # a dir on the root volume path = path[1:] new = path.replace("/", ":") return new
def to_java_compatible_path(path): if os.name == 'nt': path = path.replace('\\', '/') return path
def sanitize_path(path): ''' Perfmorms slash replacement to work on both msys and windows ''' if path is None: return None if nimp.sys.platform.is_windows() and not nimp.sys.platform.is_msys(): if path[0:1] == '/' and path[1:2].isalpha() and path[2:3] == '/': return '%s:\\%s' % (path[1], path[3:].replace('/', '\\')) if os.sep is '\\': return path.replace('/', '\\') # elif os.sep is '/': return path.replace('\\', '/')
def replace(self, pattern, repl, flags = 0): ''' Performs a re.sub on destination ''' pattern = self._format(pattern) repl = self._format(repl) def _replace_mapper(src, dest): if dest is None: raise Exception("replace() called with dest = None") dest = re.sub(pattern, repl, dest, flags = flags) yield (src, dest) return self.append(_replace_mapper) #pylint: disable=invalid-name
def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)
def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path
def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == 'win': path = self.msvs_settings.ConvertVSMacros( path, config=self.config_name) path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname) path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) return path
def path_to_posix_sep(path): """Normalize the path separator to Posix (mostly for Windows).""" return path.replace('\\', '/') if os.name == 'nt' else path
def to_png(image): _, path = tempfile.mkstemp(suffix='.svg') with open(path, 'w') as file: file.write(image) outpath = path.replace('.svg', '.png') subprocess.call(['rsvg', path, outpath]) with open(outpath, 'rb') as file: data = file.read() pathlib.Path(path).unlink() pathlib.Path(outpath).unlink() return data
def classesinmodule(module): classes = [] tree = parse_ast(os.path.abspath(module.__file__).replace('.pyc', '.py')) for c in top_level_classes(tree.body): classes.append(eval(module.__name__ + '.' + c.name)) return classes
def functionsinmodule(module): fn = [] tree = parse_ast(os.path.abspath(module.__file__).replace('.pyc', '.py')) for c in top_level_functions(tree.body): fn.append(eval(module.__name__ + '.' + c.name)) return fn
def method_header_style(header, path): name = header.split('(')[0] bold_name = '<span style="color:black;"><a href=' + \ path + ' target="_blank"><b>' + name + '</b></a></span>' # bold_name = '<span style="color:black"><b>' + name + '</b></span>' header = header.replace('self, ', '').replace('(', ' (').replace(' ', ' ') header = header.replace(name, bold_name) return '<span class="extra_h2">' + header + '</span>'