Python os.path.realpath() Examples

The following are 30 code examples for showing how to use os.path.realpath(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os.path , or try the search function .

Example 1
Project: calmjs   Author: calmjs   File: toolchain.py    License: GNU General Public License v2.0 7 votes vote down vote up
def realpath(self, spec, key):
        """
        Resolve and update the path key in the spec with its realpath,
        based on the working directory.
        """

        if key not in spec:
            # do nothing for now
            return

        if not spec[key]:
            logger.warning(
                "cannot resolve realpath of '%s' as it is not defined", key)
            return

        check = realpath(join(spec.get(WORKING_DIR, ''), spec[key]))
        if check != spec[key]:
            spec[key] = check
            logger.warning(
                "realpath of '%s' resolved to '%s', spec is updated",
                key, check
            )
        return check

    # Setup related methods 
Example 2
Project: delocate   Author: matthew-brett   File: libsana.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_rp_stripper(strip_path):
    """ Return function to strip ``realpath`` of `strip_path` from string

    Parameters
    ----------
    strip_path : str
        path to strip from beginning of strings. Processed to ``strip_prefix``
        by ``realpath(strip_path) + os.path.sep``.

    Returns
    -------
    stripper : func
        function such that ``stripper(a_string)`` will strip ``strip_prefix``
        from ``a_string`` if present, otherwise pass ``a_string`` unmodified
    """
    return get_prefix_stripper(realpath(strip_path) + os.path.sep) 
Example 3
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_toolchain_standard_not_implemented(self):
        spec = Spec()

        with self.assertRaises(NotImplementedError):
            self.toolchain(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.assemble(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.link(spec)

        # Check that the build_dir is set on the spec based on tempfile
        self.assertTrue(spec['build_dir'].startswith(
            realpath(tempfile.gettempdir())))
        # Also that it got deleted properly.
        self.assertFalse(exists(spec['build_dir'])) 
Example 4
Project: mx   Author: graalvm   File: select_jdk.py    License: GNU General Public License v2.0 6 votes vote down vote up
def find_system_jdks():
    """
    Returns a set of valid JDK directories by searching standard locations.
    """
    bases = [
        '/Library/Java/JavaVirtualMachines',
        '/usr/lib/jvm',
        '/usr/java',
        '/usr/jdk/instances',
        r'C:\Program Files\Java'
    ]
    jdks = set()
    for base in bases:
        if isdir(base):
            for n in os.listdir(base):
                jdk = join(base, n)
                mac_jdk = join(jdk, 'Contents', 'Home')
                if isdir(mac_jdk):
                    jdk = mac_jdk
                if is_valid_jdk(jdk):
                    jdks.add(realpath(jdk))
    return jdks 
Example 5
Project: ipymd   Author: rossant   File: scripts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _expand_dirs_to_files(files_or_dirs, recursive=False):
    files = []
    files_or_dirs = _ensure_list(files_or_dirs)
    for file_or_dir in files_or_dirs:
        file_or_dir = op.realpath(file_or_dir)
        if op.isdir(file_or_dir):
            # Skip dirnames starting with '.'
            if _to_skip(file_or_dir):
                continue
            # Recursively visit the directories and add the files.
            if recursive:
                files.extend(_expand_dirs_to_files([op.join(file_or_dir, file)
                             for file in os.listdir(file_or_dir)],
                             recursive=recursive))
            else:
                files.extend([op.join(file_or_dir, file)
                              for file in os.listdir(file_or_dir)])
        elif '*' in file_or_dir:
            files.extend(glob.glob(file_or_dir))
        else:
            files.append(file_or_dir)
    return files 
Example 6
Project: codimension   Author: SergeySatskiy   File: globals.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getSubdirs(path, baseNamesOnly=True, excludePythonModulesDirs=True):
    """Provides a list of sub directories for the given path"""
    subdirs = []
    try:
        path = realpath(path) + sep
        for item in os.listdir(path):
            candidate = path + item
            if isdir(candidate):
                if excludePythonModulesDirs:
                    modFile = candidate + sep + "__init__.py"
                    if exists(modFile):
                        continue
                if baseNamesOnly:
                    subdirs.append(item)
                else:
                    subdirs.append(candidate)
    except:
        pass
    return subdirs 
Example 7
Project: codimension   Author: SergeySatskiy   File: findinfilesdialog.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getParameters(self):
        """Provides a dictionary with the search parameters"""
        parameters = {'term': self.findCombo.currentText(),
                      'case': self.caseCheckBox.isChecked(),
                      'whole': self.wordCheckBox.isChecked(),
                      'regexp': self.regexpCheckBox.isChecked()}
        if self.projectRButton.isChecked():
            parameters['in-project'] = True
            parameters['in-opened'] = False
            parameters['in-dir'] = ''
        elif self.openFilesRButton.isChecked():
            parameters['in-project'] = False
            parameters['in-opened'] = True
            parameters['in-dir'] = ''
        else:
            parameters['in-project'] = False
            parameters['in-opened'] = False
            parameters['in-dir'] = realpath(
                self.dirEditCombo.currentText().strip())
        parameters['file-filter'] = self.filterCombo.currentText().strip()

        return parameters 
Example 8
Project: pytorch_geometric   Author: rusty1s   File: datasets.py    License: MIT License 6 votes vote down vote up
def get_dataset(num_points):
    name = 'ModelNet10'
    path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
    pre_transform = T.NormalizeScale()
    transform = T.SamplePoints(num_points)

    train_dataset = ModelNet(
        path,
        name='10',
        train=True,
        transform=transform,
        pre_transform=pre_transform)
    test_dataset = ModelNet(
        path,
        name='10',
        train=False,
        transform=transform,
        pre_transform=pre_transform)

    return train_dataset, test_dataset 
Example 9
Project: pytorch_geometric   Author: rusty1s   File: datasets.py    License: MIT License 6 votes vote down vote up
def get_planetoid_dataset(name, normalize_features=False, transform=None):
    path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
    dataset = Planetoid(path, name)

    if transform is not None and normalize_features:
        dataset.transform = T.Compose([T.NormalizeFeatures(), transform])
    elif normalize_features:
        dataset.transform = T.NormalizeFeatures()
    elif transform is not None:
        dataset.transform = transform

    return dataset 
Example 10
Project: jbox   Author: jpush   File: _compat.py    License: MIT License 6 votes vote down vote up
def _check_if_pyc(fname):
    """Return True if the extension is .pyc, False if .py
    and None if otherwise"""
    from imp import find_module
    from os.path import realpath, dirname, basename, splitext

    # Normalize the file-path for the find_module()
    filepath = realpath(fname)
    dirpath = dirname(filepath)
    module_name = splitext(basename(filepath))[0]

    # Validate and fetch
    try:
        fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
    except ImportError:
        raise IOError("Cannot find config file. "
                      "Path maybe incorrect! : {0}".format(filepath))
    return pytype, fileobj, fullpath 
Example 11
Project: sniffer   Author: threathunterX   File: run_driver.py    License: Apache License 2.0 6 votes vote down vote up
def bro_server(bro_file, interface="eth0", bro_path="/usr/local/bro/bin/bro"):
    u""" 跑bro服务进程 """
    # 获取绝对路径
    bro_file = path.realpath(bro_file)
    http_file = "/usr/local/bro/share/bro/base/protocols/http/main.bro"
    bro_scripts = ' '.join([bro_file, http_file])

    cmd = "sudo {bro_path} -C -b -i {interface} {bro_scripts}"
    cmd = cmd.format(bro_path=bro_path,
                     interface=interface,
                     bro_scripts=bro_scripts)

    msg = "the cmd is: %s" % cmd
    logging.info(msg)

    # change pwd to /tmp
    tmp_dir = path.join(path.dirname(path.realpath(__file__)), '../../tmp/')
    chdir(tmp_dir)

    result = run(cmd)
    logging.info(result.__dict__) 
Example 12
Project: mysql-to-sqlite3   Author: techouse   File: transporter.py    License: MIT License 6 votes vote down vote up
def _setup_logger(cls, log_file=None):
        formatter = logging.Formatter(
            fmt="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
        )
        screen_handler = logging.StreamHandler(stream=sys.stdout)
        screen_handler.setFormatter(formatter)
        logger = logging.getLogger(cls.__name__)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(screen_handler)

        if log_file:
            file_handler = logging.FileHandler(realpath(log_file), mode="w")
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

        return logger 
Example 13
Project: CHATIMUSMAXIMUS   Author: benhoff   File: settings_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_settings_helper(self):
        main_dir = path.dirname(path.realpath(__file__))
        main_dir = path.realpath(path.join(main_dir, '..', '..'))
        default_filepath = path.join(main_dir, 'default_settings.yml')
        user_filepath = path.join(main_dir, 'settings.yml')
        args = self._get_args()
        if args.settings_path:
            user_filepath = args.settings_path

        # open the default file and get version information
        with open(default_filepath) as default_filestream:
            default_filesettings = yaml.load(default_filestream)

        # FIXME: not used
        current_version = default_filesettings['version'].split('.') # flake8: noqa

        if path.exists(user_filepath):
            filepath = user_filepath
        else:
            filepath = default_filepath

        with open(filepath) as setting_file:
            self.settings = yaml.load(setting_file, _OrderedLoader)

        return SpecialDict(**self.settings) 
Example 14
Project: web2board   Author: bq   File: platformio.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def ProcessFlags(env, flags):
    for f in flags:
        if f:
            env.MergeFlags(str(f))

    # fix relative CPPPATH
    for i, p in enumerate(env.get("CPPPATH", [])):
        if isdir(p):
            env['CPPPATH'][i] = realpath(p)

    # Cancel any previous definition of name, either built in or
    # provided with a -D option // Issue #191
    undefines = [u for u in env.get("CCFLAGS", []) if u.startswith("-U")]
    if undefines:
        for undef in undefines:
            env['CCFLAGS'].remove(undef)
        env.Append(_CPPDEFFLAGS=" %s" % " ".join(undefines)) 
Example 15
Project: delocate   Author: matthew-brett   File: libsana.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def resolve_rpath(lib_path, rpaths):
    """ Return `lib_path` with its `@rpath` resolved

    If the `lib_path` doesn't have `@rpath` then it's returned as is.

    If `lib_path` has `@rpath` then returns the first `rpaths`/`lib_path`
    combination found.  If the library can't be found in `rpaths` then a
    detailed warning is printed and `lib_path` is returned as is.

    Parameters
    ----------
    lib_path : str
        The path to a library file, which may or may not start with `@rpath`.
    rpaths : sequence of str
        A sequence of search paths, usually gotten from a call to `get_rpaths`.

    Returns
    -------
    lib_path : str
        A str with the resolved libraries realpath.
    """
    if not lib_path.startswith('@rpath/'):
        return lib_path

    lib_rpath = lib_path.split('/', 1)[1]
    for rpath in rpaths:
        rpath_lib = realpath(pjoin(rpath, lib_rpath))
        if os.path.exists(rpath_lib):
            return rpath_lib

    warnings.warn(
        "Couldn't find {0} on paths:\n\t{1}".format(
            lib_path,
            '\n\t'.join(realpath(path) for path in rpaths),
            )
        )
    return lib_path 
Example 16
Project: delocate   Author: matthew-brett   File: libsana.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def wheel_libs(wheel_fname, filt_func=None):
    """ Return analysis of library dependencies with a Python wheel

    Use this routine for a dump of the dependency tree.

    Parameters
    ----------
    wheel_fname : str
        Filename of wheel
    filt_func : None or callable, optional
        If None, inspect all files for library dependencies. If callable,
        accepts filename as argument, returns True if we should inspect the
        file, False otherwise.

    Returns
    -------
    lib_dict : dict
        dictionary with (key, value) pairs of (``libpath``,
        ``dependings_dict``).  ``libpath`` is library being depended on,
        relative to wheel root path if within wheel tree.  ``dependings_dict``
        is (key, value) of (``depending_lib_path``, ``install_name``).  Again,
        ``depending_lib_path`` is library relative to wheel root path, if
        within wheel tree.
    """
    with TemporaryDirectory() as tmpdir:
        zip2dir(wheel_fname, tmpdir)
        lib_dict = tree_libs(tmpdir, filt_func)
    return stripped_lib_dict(lib_dict, realpath(tmpdir) + os.path.sep) 
Example 17
Project: delocate   Author: matthew-brett   File: test_tmpdirs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_given_directory():
    # Test InGivenDirectory
    cwd = getcwd()
    with InGivenDirectory() as tmpdir:
        assert_equal(tmpdir, abspath(cwd))
        assert_equal(tmpdir, abspath(getcwd()))
    with InGivenDirectory(MY_DIR) as tmpdir:
        assert_equal(tmpdir, MY_DIR)
        assert_equal(realpath(MY_DIR), realpath(abspath(getcwd())))
    # We were deleting the Given directory!  Check not so now.
    assert_true(isfile(MY_PATH)) 
Example 18
Project: delocate   Author: matthew-brett   File: delocate_listdeps.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    parser = OptionParser(
        usage="%s WHEEL_OR_PATH_TO_ANALYZE\n\n" % sys.argv[0] + __doc__,
        version="%prog " + __version__)
    parser.add_options([
        Option("-a", "--all",
               action="store_true",
               help="Show all dependencies, including system libs"),
        Option("-d", "--depending",
               action="store_true",
               help="Show libraries depending on dependencies")])
    (opts, paths) = parser.parse_args()
    if len(paths) < 1:
        parser.print_help()
        sys.exit(1)

    multi = len(paths) > 1
    for path in paths:
        if multi:
            print(path + ':')
            indent = '   '
        else:
            indent = ''
        if isdir(path):
            lib_dict = tree_libs(path)
            lib_dict = stripped_lib_dict(lib_dict, realpath(getcwd()) + psep)
        else:
            lib_dict = wheel_libs(path)
        keys = sorted(lib_dict)
        if not opts.all:
            keys = [key for key in keys if filter_system_libs(key)]
        if not opts.depending:
            if len(keys):
                print(indent + ('\n' + indent).join(keys))
            continue
        i2 = indent + '    '
        for key in keys:
            print(indent + key + ':')
            libs = lib_dict[key]
            if len(libs):
                print(i2 + ('\n' + i2).join(libs)) 
Example 19
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 5 votes vote down vote up
def exec_scratch_virtualenv(args):
    """
    goals:
        - get any random site-packages off of the pythonpath
        - ensure we can import virtualenv
        - ensure that we're not using the interpreter that we may need to delete
        - idempotency: do nothing if the above goals are already met
    """
    scratch = Scratch()
    if not exists(scratch.python):
        run(('virtualenv', scratch.venv))

    if not exists(join(scratch.src, 'virtualenv.py')):
        scratch_python = venv_python(scratch.venv)
        # TODO: do we allow user-defined override of which version of virtualenv to install?
        tmp = scratch.src + '.tmp'
        run((scratch_python, '-m', 'pip.__main__', 'install', 'virtualenv', '--target', tmp))

        from os import rename
        rename(tmp, scratch.src)

    import sys
    from os.path import realpath
    # We want to compare the paths themselves as sometimes sys.path is the same
    # as scratch.venv, but with a suffix of bin/..
    if realpath(sys.prefix) != realpath(scratch.venv):
        # TODO-TEST: sometimes we would get a stale version of venv-update
        exec_((scratch.python, dotpy(__file__)) + args)  # never returns

    # TODO-TEST: the original venv-update's directory was on sys.path (when using symlinking)
    sys.path[0] = scratch.src 
Example 20
Project: alibuild   Author: alisw   File: clean.py    License: GNU General Public License v3.0 5 votes vote down vote up
def decideClean(workDir, architecture, aggressiveCleanup):
  """ Decides what to delete, without actually doing it:
      - Find all the symlinks in "BUILD"
      - Find all the directories in "BUILD"
      - Schedule a directory for deletion if it does not have a symlink
  """
  symlinksBuild = [os.readlink(x) for x in glob.glob("%s/BUILD/*-latest*" % workDir)]
  # $WORK_DIR/TMP should always be cleaned up. This does not happen only
  # in the case we run out of space while unpacking.
  # $WORK_DIR/<architecture>/store can be cleaned up as well, because
  # we do not need the actual tarballs after they have been built.
  toDelete = ["%s/TMP" % workDir]
  if aggressiveCleanup:
    toDelete += ["%s/TARS/%s/store" % (workDir, architecture),
                 "%s/SOURCES" % (workDir)]
  allBuildStuff = glob.glob("%s/BUILD/*" % workDir)
  toDelete += [x for x in allBuildStuff
               if not path.islink(x) and not basename(x) in symlinksBuild]
  installGlob ="%s/%s/*/" % (workDir, architecture)
  installedPackages = set([dirname(x) for x in glob.glob(installGlob)])
  symlinksInstall = []
  for x in installedPackages:
    symlinksInstall += [path.realpath(y) for y in glob.glob(x + "/latest*")]
  toDelete += [x for x in glob.glob(installGlob+ "*")
               if not path.islink(x) and not path.realpath(x) in symlinksInstall]
  toDelete = [x for x in toDelete if path.exists(x)]
  return toDelete 
Example 21
Project: calmjs   Author: calmjs   File: toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _validate_build_target(self, spec, target):
        """
        Essentially validate that the target is inside the build_dir.
        """

        if not realpath(target).startswith(spec[BUILD_DIR]):
            raise ValueError('build_target %s is outside build_dir' % target)

    # note that in the following methods, a shorthand notation is used
    # for some of the arguments: nearly all occurrences of source means
    # sourcepath, and target means targetpath. 
Example 22
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_toolchain_calf_with_build_dir_null(self):
        spec = Spec(build_dir=None)

        with self.assertRaises(NotImplementedError):
            self.toolchain(spec)

        # While build_dir is defined, no value was assigned.  See that
        # the process will give it a new one.
        self.assertTrue(spec['build_dir'].startswith(
            realpath(tempfile.gettempdir())))
        # Also that it got deleted properly.
        self.assertFalse(exists(spec['build_dir'])) 
Example 23
Project: calmjs   Author: calmjs   File: test_testing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def mkdtemp(self):
        self.count += 1
        result = realpath(tempfile.mkdtemp())
        self.dirs.append(result)
        return result 
Example 24
Project: calmjs   Author: calmjs   File: test_testing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.tmpdir = realpath(tempfile.mkdtemp())
        tempfile.tempdir = self.tmpdir 
Example 25
Project: calmjs   Author: calmjs   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def mkdtemp_realpath():
    return realpath(tempfile.mkdtemp()) 
Example 26
Project: mx   Author: graalvm   File: mx_ide_intellij.py    License: GNU General Public License v2.0 5 votes vote down vote up
def intellij_get_python_sdk_name(sdks):
    exe = realpath(sys.executable)
    if exe in sdks:
        sdk = sdks[exe]
        if sdk['type'] == intellij_python_sdk_type:
            return sdk['name']
    return "Python {v[0]}.{v[1]} ({exe})".format(v=sys.version_info, exe=exe) 
Example 27
Project: sslyze   Author: nabla-c0d3   File: trust_store_repository.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_script_dir(follow_symlinks: bool = True) -> Path:
    # Getting the path to the trust stores is tricky due to subtle differences on OS X, Linux and Windows
    if getattr(sys, "frozen", False):
        # py2exe, PyInstaller, cx_Freeze
        path = Path(sys.executable).absolute()
    else:
        path = Path(inspect.getabsfile(_get_script_dir))
    if follow_symlinks:
        path = Path(realpath(path))
    return path.parent 
Example 28
Project: ipymd   Author: rossant   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _script_dir():
    return op.dirname(op.realpath(__file__)) 
Example 29
Project: ipymd   Author: rossant   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _test_file_path(basename, format=None):
    """Return the full path to an example filename in the 'examples'
    directory."""
    if format is not None:
        file_extension = format_manager().file_extension(format)
        filename = basename + '.' + format + file_extension
    else:
        # format=None ==> .py test file
        filename = basename + '.py'
    return op.realpath(op.join(_script_dir(), '../../../examples', filename)) 
Example 30
Project: ipymd   Author: rossant   File: scripts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _common_root(files):
    files = [op.realpath(file) for file in files]
    root = op.commonprefix(files)
    if not op.exists(root):
        root = op.dirname(root)
    if root:
        assert op.exists(root)
        assert op.isdir(root), root
    return root