Python os.path.realpath() Examples

The following are 30 code examples of os.path.realpath(). 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: toolchain.py    From calmjs with 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
Source File: findinfilesdialog.py    From codimension with 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 #3
Source File: scripts.py    From ipymd with 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 #4
Source File: select_jdk.py    From mx with 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
Source File: _compat.py    From jbox with 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 #6
Source File: test_toolchain.py    From calmjs with 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 #7
Source File: run_driver.py    From sniffer with 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 #8
Source File: datasets.py    From pytorch_geometric with 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
Source File: transporter.py    From mysql-to-sqlite3 with 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 #10
Source File: settings_model.py    From CHATIMUSMAXIMUS with 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 #11
Source File: platformio.py    From web2board with 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 #12
Source File: globals.py    From codimension with 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 #13
Source File: libsana.py    From delocate with 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 #14
Source File: setup.py    From python-spark with MIT License 5 votes vote down vote up
def get_srcdir():
    filename = osp.normcase(osp.dirname(osp.abspath(__file__)))
    return osp.realpath(filename) 
Example #15
Source File: sysconfig.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example #16
Source File: sysconfig.py    From Python24 with MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example #17
Source File: __init__.py    From bigcode-tools with MIT License 5 votes vote down vote up
def __init__(self, methodName='runTest'):
        super(TestCase, self).__init__(methodName)
        self.fixtures_path = path.realpath(path.join(__file__, "../fixtures")) 
Example #18
Source File: baseutil.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def get_plugin_path():
    from os.path import dirname, realpath
    return dirname(realpath(__file__)) 
Example #19
Source File: utils.py    From ec2-gazua with MIT License 5 votes vote down vote up
def join_path(file, path):
    return join(dirname(realpath(file)), path) 
Example #20
Source File: test_pls2.py    From hoggorm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dump_res(rname, dat):
    """
    Dumps information to file if reference data is missing or difference is larger than tolerance.
    """
    dumpfolder = osp.realpath(osp.dirname(__file__))
    dumpfn = "dump_PLS2_{}.tsv".format(rname.lower())
    np.savetxt(osp.join(dumpfolder, dumpfn), dat, fmt='%.9e', delimiter='\t') 
Example #21
Source File: functionsbrowsermodel.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def onFSChanged(self, addedPythonFiles, deletedPythonFiles):
        """Triggered when some files appeared or disappeared"""
        needUpdate = False
        itemsToDelete = []
        for path in deletedPythonFiles:
            for item in self.rootItem.childItems:
                if realpath(path) == realpath(item.getPath()):
                    itemsToDelete.append(item)

        for item in itemsToDelete:
            needUpdate = True
            self.removeTreeItem(item)

        for path in addedPythonFiles:
            try:
                info = self.globalData.briefModinfoCache.get(path)
            except:
                # It could be that a file was created and deleted straight
                # away. In this case the cache will generate an exception.
                continue
            for funcObj in info.functions:
                needUpdate = True
                newItem = TreeViewFunctionItem(self.rootItem, funcObj)
                newItem.appendData([basename(path), funcObj.line])
                newItem.setPath(path)
                self.addTreeItem(self.rootItem, newItem)
        return needUpdate 
Example #22
Source File: sysconfig.py    From meddle with MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example #23
Source File: common.py    From P3DModuleBuilder with MIT License 5 votes vote down vote up
def first_existing_path(paths, required_file=None, base_dir=None, on_error=""):
    """ Returns the first path out of a given list of paths which exists.
    If required_file is set, the path additionally has to contain the given
    filename """
    for pth in paths:
        if base_dir:
            pth = join(base_dir, pth)
        if isdir(pth) and (required_file is None or isfile(join(pth, required_file))):
            return realpath(pth)
    if on_error:
        print_error("\n" + on_error + "\n")
    print_error("We tried to find a folder or file on the following paths:")
    for pth in paths:
        print_error("[-]", realpath(join(base_dir, pth)))
    fatal_error("Failed to locate path") 
Example #24
Source File: common.py    From P3DModuleBuilder with MIT License 5 votes vote down vote up
def is_subdirectory(base, subdir):
    """ Returns whether subdir is the same or subdirectory of base """
    base_real = realpath(base)
    sub_real = realpath(subdir)
    return sub_real.startswith(base_real) 
Example #25
Source File: common.py    From P3DModuleBuilder with MIT License 5 votes vote down vote up
def get_output_dir():
    """ Returns the output directory where CMake generates the build files into """
    return realpath(join(get_basepath(), get_output_name())) 
Example #26
Source File: common.py    From P3DModuleBuilder with MIT License 5 votes vote down vote up
def get_script_dir():
    """ Returns the name of the directory the scripts are located in """
    return dirname(realpath(__file__)) 
Example #27
Source File: path_checker.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def external_disk_link_exists(self):
        real_link_path = path.realpath(self.platform_config.get_disk_link())
        self.log.info('real link path: {0}'.format(real_link_path))

        external_disk_path = self.platform_config.get_external_disk_dir()
        self.log.info('external disk path: {0}'.format(external_disk_path))

        link_exists = real_link_path == external_disk_path
        self.log.info('link exists: {0}'.format(link_exists))

        return link_exists 
Example #28
Source File: globalsbrowsermodel.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def onFSChanged(self, addedPythonFiles, deletedPythonFiles):
        """Triggered when some files appeared or disappeared"""
        needUpdate = False
        itemsToDelete = []
        for path in deletedPythonFiles:
            for item in self.rootItem.childItems:
                if realpath(path) == realpath(item.getPath()):
                    itemsToDelete.append(item)

        for item in itemsToDelete:
            needUpdate = True
            self.removeTreeItem(item)

        for path in addedPythonFiles:
            try:
                info = self.globalData.briefModinfoCache.get(path)
            except:
                # It could be that a file was created and deleted straight
                # away. In this case the cache will generate an exception.
                continue
            for globalObj in info.globals:
                needUpdate = True
                newItem = TreeViewGlobalItem(self.rootItem, globalObj)
                newItem.appendData([basename(path), globalObj.line])
                newItem.setPath(path)
                self.addTreeItem(self.rootItem, newItem)
        return needUpdate 
Example #29
Source File: sysconfig.py    From jbox with MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example #30
Source File: datasets.py    From pytorch_geometric with MIT License 5 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