Python os.path.replace() Examples

The following are 30 code examples of os.path.replace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os.path , or try the search function .
Example #1
Source File: files.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
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 in self.aliases:
            m = regex.match(path)
            if m:
                new = path.replace(m.group(0), result)
                new = new.replace(sep(path), sep(result))
                new = canonical_filename(new)
                return new
        return path 
Example #2
Source File: conftest.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def run_command(quteproc, server, tmpdir, command):
    """Run a qutebrowser command.

    The suffix "with count ..." can be used to pass a count to the command.
    """
    if 'with count' in command:
        command, count = command.split(' with count ')
        count = int(count)
    else:
        count = None

    invalid_tag = ' (invalid command)'
    if command.endswith(invalid_tag):
        command = command[:-len(invalid_tag)]
        invalid = True
    else:
        invalid = False

    command = command.replace('(port)', str(server.port))
    command = command.replace('(testdata)', testutils.abs_datapath())
    command = command.replace('(tmpdir)', str(tmpdir))
    command = command.replace('(dirsep)', os.sep)
    command = command.replace('(echo-exe)', _get_echo_exe_path())

    quteproc.send_cmd(command, count=count, invalid=invalid) 
Example #3
Source File: test_filescanner.py    From py-ipfs-http-client with MIT License 6 votes vote down vote up
def test_glob_matching(
		monkeypatch,
		pattern: ty.Union[ty.AnyStr, filescanner.re_pattern_t, ty.List[ty.Union[ty.AnyStr, filescanner.re_pattern_t]]],
		path: ty.AnyStr,
		is_dir: bool,
		descend: bool,
		report: bool,
		kwargs: ty.Dict[str, bool]
):
	# Hopefully useless sanity check
	assert os.path.sep == "/" or os.path.altsep == "/"
	
	slash = "/"         if isinstance(path, str) else b"/"  # type: ty.AnyStr
	sep   = os.path.sep if isinstance(path, str) else os.fsencode(os.path.sep)  # type: ty.AnyStr
	
	path = path.replace(slash, sep)
	
	matcher = filescanner.matcher_from_spec(pattern, **kwargs)
	assert matcher.should_descend(path)               is descend
	assert matcher.should_report(path, is_dir=is_dir) is report 
Example #4
Source File: pydevd_filtering.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def glob_matches_path(path, pattern, sep=os.sep, altsep=os.altsep):
    if altsep:
        pattern = pattern.replace(altsep, sep)
        path = path.replace(altsep, sep)

    drive = ''
    if len(path) > 1 and path[1] == ':':
        drive, path = path[0], path[2:]

    if drive and len(pattern) > 1:
        if pattern[1] == ':':
            if drive.lower() != pattern[0].lower():
                return False
            pattern = pattern[2:]

    patterns = pattern.split(sep)
    paths = path.split(sep)
    if paths:
        if paths[0] == '':
            paths = paths[1:]
    if patterns:
        if patterns[0] == '':
            patterns = patterns[1:]

    return _check_matches(patterns, paths) 
Example #5
Source File: files.py    From coveragepy with Apache License 2.0 6 votes vote down vote up
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 in self.aliases:
            m = regex.match(path)
            if m:
                new = path.replace(m.group(0), result)
                new = new.replace(sep(path), sep(result))
                new = canonical_filename(new)
                return new
        return path 
Example #6
Source File: test_jinja.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_resource_url():
    """Test resource_url() which can be used from templates."""
    data = jinja.render('test2.html')
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert url.scheme() == 'file'

    path = url.path()

    if utils.is_windows:
        path = path.lstrip('/')
        path = path.replace('/', os.sep)

    with open(path, 'r', encoding='utf-8') as f:
        assert f.read().splitlines()[0] == "Hello World!" 
Example #7
Source File: intelc.py    From pivy with ISC License 6 votes vote down vote up
def get_intel_registry_value(valuename, version=None, abi=None):
    """
    Return a value from the Intel compiler registry tree. (Windows only)
    """
    # Open the key:
    if is_win64:
        K = 'Software\\Wow6432Node\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
    else:
        K = 'Software\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
    try:
        k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K)
    except SCons.Util.RegError:
        raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi))

    # Get the value:
    try:
        v = SCons.Util.RegQueryValueEx(k, valuename)[0]
        return v  # or v.encode('iso-8859-1', 'replace') to remove unicode?
    except SCons.Util.RegError:
        raise MissingRegistryError("%s\\%s was not found in the registry."%(K, valuename)) 
Example #8
Source File: quteprocess.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def path_to_url(self, path, *, port=None, https=False):
        """Get a URL based on a filename for the localhost webserver.

        URLs like about:... and qute:... are handled specially and returned
        verbatim.
        """
        special_schemes = ['about:', 'qute:', 'chrome:', 'view-source:',
                           'data:', 'http:', 'https:']
        server = self.request.getfixturevalue('server')
        server_port = server.port if port is None else port

        if any(path.startswith(scheme) for scheme in special_schemes):
            path = path.replace('(port)', str(server_port))
            return path
        else:
            return '{}://localhost:{}/{}'.format(
                'https' if https else 'http',
                server_port,
                path if path != '/' else '') 
Example #9
Source File: ipython_widget.py    From Computable with MIT License 6 votes vote down vote up
def _process_execute_error(self, msg):
        """ Reimplemented for IPython-style traceback formatting.
        """
        content = msg['content']
        traceback = '\n'.join(content['traceback']) + '\n'
        if False:
            # FIXME: For now, tracebacks come as plain text, so we can't use
            # the html renderer yet.  Once we refactor ultratb to produce
            # properly styled tracebacks, this branch should be the default
            traceback = traceback.replace(' ', ' ')
            traceback = traceback.replace('\n', '<br/>')

            ename = content['ename']
            ename_styled = '<span class="error">%s</span>' % ename
            traceback = traceback.replace(ename, ename_styled)

            self._append_html(traceback)
        else:
            # This is the fallback for now, using plain text with ansi escapes
            self._append_plain_text(traceback) 
Example #10
Source File: setup.py    From GMatch4py with MIT License 6 votes vote down vote up
def makeExtension(extName):
    global libs
    extPath = extName.replace(".", os.path.sep)+".pyx"

    ## For Mojave Users
    if platform.system() == "Darwin":
        if "10.14" in platform.mac_ver()[0]:
            return Extension(
            extName,
            [extPath],include_dirs=[np.get_include()],language='c++',libraries=libs,
            extra_compile_args=["-stdlib=libc++"]
            )
    
    return Extension(
        extName,
        [extPath],include_dirs=[np.get_include()],language='c++',libraries=libs,
        #extra_compile_args = ["-O0", "-fopenmp"],extra_link_args=['-fopenmp']

        )

# get the list of extensions 
Example #11
Source File: page_hierarchy.py    From pelican-page-hierarchy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_path(page, settings):
    ''' Return the dirname relative to PAGE_PATHS prefix. '''
    path = os.path.split(page.get_relative_source_path())[0] + '/'
    path = path.replace( os.path.sep, '/' )
    # Try to lstrip the longest prefix first
    for prefix in sorted(settings['PAGE_PATHS'], key=len, reverse=True):
        if not prefix.endswith('/'): prefix += '/'
        if path.startswith(prefix):
            return path[len(prefix):-1]
    raise UnexpectedException('Page outside of PAGE_PATHS ?!?') 
Example #12
Source File: test_context.py    From xcube with MIT License 5 votes vote down vote up
def test_get_s3_bucket_mapping(self):
        ctx = new_test_service_context()
        bucket_mapping = ctx.get_s3_bucket_mapping()
        self.assertEqual(['demo'],
                         list(bucket_mapping.keys()))
        path = bucket_mapping['demo']
        self.assertTrue(os.path.isabs(path))
        self.assertTrue(path.replace('\\', '/').endswith('examples/serve/demo/cube-1-250-250.zarr')) 
Example #13
Source File: setup.py    From GMatch4py with MIT License 5 votes vote down vote up
def scandir(dir, files=[]):
    for file in os.listdir(dir):
        path = os.path.join(dir, file)
        if os.path.isfile(path) and path.endswith(".pyx"):
            files.append(path.replace(os.path.sep, ".")[:-4])
        elif os.path.isdir(path):
            scandir(path, files)
    return files

# generate an Extension object from its dotted name 
Example #14
Source File: ninja.py    From StarsAndClown with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #15
Source File: ninja.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #16
Source File: ninja.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #17
Source File: ninja.py    From StarsAndClown with GNU General Public License v3.0 5 votes vote down vote up
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("'", "'" + '"\'"' + "'")  + "'" 
Example #18
Source File: ninja.py    From StarsAndClown with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #19
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def escape( str ):
    str = str.replace("&", "&amp;")
    str = str.replace("<", "&lt;")
    str = str.replace(">", "&gt;")
    str = str.replace("\"", "&quot;")
    return str 
Example #20
Source File: cppdep.py    From cppdep with GNU General Public License v3.0 5 votes vote down vote up
def path_to_posix_sep(path):
    """Normalize the path separator to Posix (mostly for Windows)."""
    return path.replace('\\', '/') if os.name == 'nt' else path 
Example #21
Source File: test_CLI.py    From authenticator with MIT License 5 votes vote down vote up
def _side_effect_expand_user(self, path):
        if not path.startswith("~"):
            return path
        path = path.replace("~", self.temp_dir_path.name)
        return path

    # ------------------------------------------------------------------------+
    # setup, teardown, noop
    # ------------------------------------------------------------------------+ 
Example #22
Source File: files.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def unicode_filename(filename):
        """Return a Unicode version of `filename`."""
        if isinstance(filename, str):
            encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
            filename = filename.decode(encoding, "replace")
        return filename 
Example #23
Source File: recipe-442521.py    From code with MIT License 5 votes vote down vote up
def covert_unc(host, path):
    """ Convert a file path on a host to a UNC path."""
    return ''.join(['\\\\', host, '\\', path.replace(':', '$')]) 
Example #24
Source File: menu.py    From NukeToolSet with MIT License 5 votes vote down vote up
def replace_path(self, path):
        """
        replace path
        :param path:
        :return:
        """
        final_path = path.replace('\\', '/')
        return final_path 
Example #25
Source File: NinjaWriter.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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("'", "'" + '"\'"' + "'") + "'" 
Example #26
Source File: NinjaWriter.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _Define(self, 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 self._QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) 
Example #27
Source File: NinjaWriter.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #28
Source File: NinjaWriter.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #29
Source File: splitter.py    From Gap with Apache License 2.0 5 votes vote down vote up
def load(self, path):
        """ Load the NLP tokenized string from storage """
        if not isinstance(path, str):
            raise TypeError("Path must be a string")
        if os.path.isfile(path) == False:
                raise FileNotFoundError("Not a valid path")
        with open(path, 'r', encoding='utf-8') as f:
            self._words = Words()
            self._words._words = json.load(f)
        path = path.replace('.json', '.txt')
        with open(path, 'r', encoding='utf-8') as f:
            self._text = f.read() 
Example #30
Source File: bazelci.py    From continuous-integration with Apache License 2.0 5 votes vote down vote up
def execute_command_and_get_output(args, shell=False, fail_if_nonzero=True, print_output=True):
    eprint(" ".join(args))
    process = subprocess.run(
        args,
        shell=shell,
        check=fail_if_nonzero,
        env=os.environ,
        stdout=subprocess.PIPE,
        errors="replace",
        universal_newlines=True,
    )
    if print_output:
        eprint(process.stdout)

    return process.stdout