Python os.path.realpath() Examples

The following are code examples for showing how to use os.path.realpath(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: flasky   Author: RoseOu   File: _compat.py    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 2
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedSetup.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def getCurrentColor(self):
        myfile = self.skin_base_dir + self.color_file
        if not path.exists(myfile):
            if path.exists(self.skin_base_dir + self.default_color_file):
                if path.islink(myfile):
                    remove(myfile)
                chdir(self.skin_base_dir)
                symlink(self.default_color_file, self.color_file)
            else:
                return None
        filename = path.realpath(myfile)
        filename = path.basename(filename)

        search_str = 'colors_'
        friendly_name = filename.replace(search_str, "")
        friendly_name = friendly_name.replace(".xml", "")
        friendly_name = friendly_name.replace("_", " ")
        return (filename, friendly_name) 
Example 3
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedSetup.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def getCurrentFont(self):
        myfile = self.skin_base_dir + self.font_file
        if not path.exists(myfile):
            if path.exists(self.skin_base_dir + self.default_font_file):
                if path.islink(myfile):
                    remove(myfile)
                chdir(self.skin_base_dir)
                symlink(self.default_font_file, self.font_file)
            else:
                return None
        filename = path.realpath(myfile)
        filename = path.basename(filename)

        search_str = 'font_'
        friendly_name = filename.replace(search_str, "")
        friendly_name = friendly_name.replace(".xml", "")
        friendly_name = friendly_name.replace("_", " ")
        return (filename, friendly_name) 
Example 4
Project: calmjs   Author: calmjs   File: toolchain.py    GNU General Public License v2.0 6 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 5
Project: calmjs   Author: calmjs   File: test_toolchain.py    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 6
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def get_output_root(self, platformDependent=False):
        """
        Gets the root of the directory hierarchy under which generated artifacts for this
        suite such as class files and annotation generated sources should be placed.
        """
        if not self._outputRoot:
            outputRoot = self._get_early_suite_dict_property('outputRoot')
            if outputRoot:
                self._outputRoot = realpath(_make_absolute(outputRoot.replace('/', os.sep), self.dir))
            elif get_env('MX_ALT_OUTPUT_ROOT') is not None:
                self._outputRoot = realpath(_make_absolute(join(get_env('MX_ALT_OUTPUT_ROOT'), self.name), self.dir))
            else:
                self._outputRoot = self.getMxCompatibility().getSuiteOutputRoot(self)
        if platformDependent:
            return os.path.join(self._outputRoot, get_os() + '-' + get_arch())
        else:
            return self._outputRoot 
Example 7
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def _verify_layout(self):
        output = realpath(self.get_output())
        for destination, sources in self.layout.items():
            if not isinstance(destination, str):
                abort("Destination (layout keys) should be a string", context=self)
            if not isinstance(sources, list):
                sources = [sources]
            if not destination:
                abort("Destination (layout keys) can not be empty", context=self)
            for source in sources:
                if not isinstance(source, (str, dict)):
                    abort("Error in '{}': sources should be strings or dicts".format(destination), context=self)
            if isabs(destination):
                abort("Invalid destination: '{}': destination should not be absolute".format(destination), context=self)
            final_destination = normpath(join(output, destination))
            if not final_destination.startswith(output):
                abort("Invalid destination: '{}': destination should not escape the output directory ('{}' is not in '{}')".format(destination, final_destination, output), context=self)
            if not destination.endswith('/'):
                if len(sources) > 1:
                    abort("Invalid layout: cannot copy multiple files to a single destination: '{dest}'\n"
                          "Should the destination be a directory: '{dest}/'? (note the trailing slash)".format(dest=destination), context=self)
                if len(sources) < 1:
                    abort("Invalid layout: no file to copy to '{dest}'\n"
                          "Do you want an empty directory: '{dest}/'? (note the trailing slash)".format(dest=destination), context=self) 
Example 8
Project: https-github.com-ZhengyaoJiang-PGPortfolio   Author: stevep2007   File: generate.py    GNU General Public License v3.0 6 votes vote down vote up
def add_packages(config, repeat=1):
    train_dir = "train_package"
    package_dir = path.realpath(__file__).replace('pgportfolio/autotrain/generate.pyc',train_dir)\
        .replace("pgportfolio\\autotrain\\generate.pyc", train_dir)\
                  .replace('pgportfolio/autotrain/generate.py',train_dir)\
        .replace("pgportfolio\\autotrain\\generate.py", train_dir)
    all_subdir = [int(s) for s in os.listdir(package_dir) if os.path.isdir(package_dir+"/"+s)]
    if all_subdir:
        max_dir_num = max(all_subdir)
    else:
        max_dir_num = 0
    indexes = []

    for i in range(repeat):
        max_dir_num += 1
        directory = package_dir+"/"+str(max_dir_num)
        config["random_seed"] = i
        os.makedirs(directory)
        indexes.append(max_dir_num)
        with open(directory + "/" + "net_config.json", 'w') as outfile:
            json.dump(config, outfile, indent=4, sort_keys=True)
    logging.info("create indexes %s" % indexes)
    return indexes 
Example 9
Project: vo_single_camera_sos   Author: ubuntuslave   File: pose_est_tools.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, camera_model, show_3D_points = False, **kwargs):
        self.camera_model = camera_model
        self.show_3D_points = show_3D_points
        self.save_correspondence_images = kwargs.get("save_correspondence_images", False)
        self.results_path = kwargs.get("results_path", "~/temp")
        self.correspondence_images_path = ""
        if self.save_correspondence_images:
            self.correspondence_images_path = join(realpath(expanduser(self.results_path)), "final_correspondences_images")
            make_sure_path_exists(self.correspondence_images_path)
        self.T_C_wrt_S_init = tr.identity_matrix()
        self.T_C_curr_frame_wrt_S_est = tr.identity_matrix()
        self.xyz_homo_points_wrt_C_inliers = []  # XYZ homogeneous coordinates of inliers for the estimated pose
        self.rgb_points_inliers = []  # Colors for inlier points
        self.num_tracked_correspondences = 0  # RANSAC inliers of current tracking
        self.inlier_tracked_correspondences_ratio = 0.  # RANSAC inliers of current tracking
        self.number_of_cams = 1  # Just a default number that should be changed if needed
        self.T_Ckey_wrt_S_est_list = []  # This should only contain a list of keyframe poses
        self.set_global_parameters_for_tracking()  # This is done here because we are attempting to unify the trackers inheriting from this class 
Example 10
Project: codimension   Author: SergeySatskiy   File: globals.py    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 11
Project: codimension   Author: SergeySatskiy   File: briefmodinfocache.py    GNU General Public License v3.0 6 votes vote down vote up
def get(self, path):
        """Provides the required modinfo"""
        path = realpath(path)
        try:
            modInfo = self.__cache[path]
            if not exists(path):
                del self.__cache[path]
                raise Exception("Cannot open " + path)

            lastModTime = getmtime(path)
            if lastModTime <= modInfo[0]:
                return modInfo[1]

            # update the key
            info = getBriefModuleInfoFromFile(path)
            self.__cache[path] = (lastModTime, info)
            return info
        except KeyError:
            if not exists(path):
                raise Exception("Cannot open " + path)

            info = getBriefModuleInfoFromFile(path)
            self.__cache[path] = (getmtime(path), info)
            return info 
Example 12
Project: pytorch_geometric   Author: rusty1s   File: datasets.py    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 13
Project: jbox   Author: jpush   File: _compat.py    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 14
Project: pyblish-win   Author: pyblish   File: sysconfig.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 15
Project: voice-recognition   Author: golabies   File: speech_to_text.py    MIT License 5 votes vote down vote up
def read_audio(self):
        '''reads path of audio file'''
        self.audiofile = path.join(path.dirname(path.realpath("E:\parisa\projects\\voice_recognition\\voice-recognition-master\\wave_files")), "english.wav") 
Example 16
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 17
Project: spqrel_tools   Author: LCAS   File: map_bridge.py    MIT License 5 votes vote down vote up
def __init__(self, memory_service, mapprops, topomap):

        self.memory_service = memory_service

        self.props = self.read_map_properties(mapprops)

        self.mapprops_path = realpath(dirname(mapprops))
        imgpath = join(self.mapprops_path, self.props['image'])

        self.map_img = Image.open(imgpath) 
Example 18
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, fs, root):
        self.fs = fs
        self.root = realpath(root)
        self.rwlock = Lock() 
Example 19
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, root, mountpoint):
        self.root = realpath(root)
        self.mountpoint = realpath(mountpoint)
        print 'root %r -> mount %r' % (self.root, self.mountpoint)
        self.rwlock = Lock()
        self._caches = {} 
Example 20
Project: flasky   Author: RoseOu   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 21
Project: sic   Author: Yanixos   File: sysconfig.py    GNU General Public License v3.0 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 22
Project: domain_gen   Author: rootVIII   File: rpath.py    MIT License 5 votes vote down vote up
def __init__(self):
        p = realpath(__file__)
        if ':' not in p:
            self.rpath = p[:-14]
        else:
            self.rpath = p[2:].replace('\\', '/')[:-14] 
Example 23
Project: AshsSDK   Author: thehappydinoa   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 24
Project: mealpy   Author: edmundmok   File: venv_update.py    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 25
Project: calmjs   Author: calmjs   File: toolchain.py    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 26
Project: calmjs   Author: calmjs   File: test_toolchain.py    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 27
Project: calmjs   Author: calmjs   File: test_testing.py    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 28
Project: calmjs   Author: calmjs   File: test_testing.py    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 29
Project: calmjs   Author: calmjs   File: utils.py    GNU General Public License v2.0 5 votes vote down vote up
def mkdtemp_realpath():
    return realpath(tempfile.mkdtemp()) 
Example 30
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def make_archive(self):
        self._verify_layout()
        output = realpath(self.get_output())
        with self.archive_factory(self.path,
                                  kind=self.localExtension(),
                                  duplicates_action='warn',
                                  context=self,
                                  reset_user_group=getattr(self, 'reset_user_group', False),
                                  compress=self.compress) as arc:
            for destination, source in self._walk_layout():
                self._install_source(source, output, destination, arc)
        self._persist_layout()
        self._persist_linky_state() 
Example 31
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def _is_sane_name(self, m, dst):
        return os.path.realpath(os.path.join(dst, m)).startswith(os.path.realpath(dst)) 
Example 32
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def getArchivableResults(self, use_relpath=True, single=False):
        path = realpath(self.get_path(False))
        yield path, _map_to_maven_dist_name(self.name) + '.' + get_file_extension(path) 
Example 33
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def get_vc_root(directory, abortOnError=True):
        """
        Attempt to determine what kind of VCS is associated with `directory`.
        Return the VC and its root directory or (None, None) if it cannot be determined.

        If `directory` is contained in multiple VCS, the one with the deepest nesting is returned.

        :param str directory: a valid path to a potentially version controlled directory
        :param bool abortOnError: if an error occurs, abort mx operations
        :return: a tuple containing an instance of VC or None if it cannot be
        determined followed by the root of the repository or None.
        :rtype: :class:`VC`, str
        """
        best_root = None
        best_vc = None
        for vcs in _vc_systems:
            vcs.check()
            root = vcs.root(directory, abortOnError=False)
            if root is None:
                continue
            root = realpath(os.path.abspath(root))
            if best_root is None or len(root) > len(best_root):  # prefer more nested vcs roots
                best_root = root
                best_vc = vcs
        if abortOnError and best_root is None:
            abort('cannot determine VC and root for ' + directory)
        return best_vc, best_root 
Example 34
Project: mx   Author: graalvm   File: mx.py    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 35
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def scloneimports(args):
    """clone the imports of an existing suite"""
    parser = ArgumentParser(prog='mx scloneimports')
    parser.add_argument('--source', help='path to primary suite')
    parser.add_argument('--manual', action='store_true', help='this option has no effect, it is deprecated')
    parser.add_argument('--ignore-version', action='store_true', help='ignore version mismatch for existing suites')
    parser.add_argument('nonKWArgs', nargs=REMAINDER, metavar='source')
    args = parser.parse_args(args)

    warn("The scloneimports command is deprecated and is scheduled for removal.")

    # check for non keyword args
    if args.source is None:
        args.source = _kwArg(args.nonKWArgs)
    if not args.source:
        abort('scloneimports: path to primary suite missing')
    if not os.path.isdir(args.source):
        abort(args.source + ' is not a directory')

    if args.nonKWArgs:
        warn("Some extra arguments were ignored: " + ' '.join((pipes.quote(a) for a in args.nonKWArgs)))

    if args.manual:
        warn("--manual argument is deprecated and has been ignored")
    if args.ignore_version:
        _opts.version_conflict_resolution = 'ignore'

    source = realpath(args.source)
    mxDir = _is_suite_dir(source)
    if not mxDir:
        abort("'{}' is not an mx suite".format(source))
    _discover_suites(mxDir, load=False, register=False, update_existing=True) 
Example 36
Project: Pesquisas   Author: danilopcarlotti   File: transcrever_audio.py    Apache License 2.0 5 votes vote down vote up
def transcrever(self,audio = None):
		if audio:
			AUDIO_FILE = audio
		else:
			AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "audio.wav")
		r = sr.Recognizer()
		with sr.AudioFile(AUDIO_FILE) as source:
			audio = r.record(source)
		try:
			return ''.join([l for l in r.recognize_google(audio,language='pt').split(' ')])
		except:
		    return False 
Example 37
Project: Volux   Author: DrTexx   File: temperatures.py    GNU General Public License v3.0 5 votes vote down vote up
def _core_hot(self, hot_core):
        plyer.notification.notify(
            title="Core Hot",
            message="{} is running hot!".format(hot_core.label),
            app_name=self.app_name,
            app_icon=realpath("fire.ico"),  # must be .ico on Windows
            timeout=10,
        ) 
Example 38
Project: Volux   Author: DrTexx   File: temperatures.py    GNU General Public License v3.0 5 votes vote down vote up
def _core_critical(self, critical_core):
        plyer.notification.notify(
            title="Core Critical",
            message="{} at critical temperature!".format(critical_core.label),
            app_name=self.app_name,
            app_icon=realpath("exclaimation.png"),
            timeout=15,
        ) 
Example 39
Project: hnbex-cli   Author: ihabunek   File: commands.py    GNU General Public License v3.0 5 votes vote down vote up
def abspath(path):
    return join(realpath(dirname(__file__)), path) 
Example 40
Project: Repobot   Author: Desgard   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 41
Project: jenkins-plugin-resolver   Author: hypergig   File: tests.py    MIT License 5 votes vote down vote up
def setUp(self, mock_urlopen):
        test_json_loc = '{}/test-update-center.json'.format(
            dirname(realpath(__file__)))
        with open(test_json_loc) as f:
            test_json = f.read()

        # mock the read return
        mock = Mock()
        mock.read.return_value = test_json
        mock_urlopen.return_value = mock
        self.jpr = JenkinsPluginResolver() 
Example 42
Project: JukeBox   Author: gauravsarkar97   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 43
Project: chattR   Author: patrickstocklin   File: sysconfig.py    GNU General Public License v2.0 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 44
Project: Flask_Blog   Author: sugarguo   File: sysconfig.py    GNU General Public License v3.0 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 45
Project: LaserTOF   Author: kyleuckert   File: test_tmpdirs.py    MIT License 5 votes vote down vote up
def test_given_directory():
    # Test InGivenDirectory
    cwd = getcwd()
    with in_dir() as tmpdir:
        assert_equal(tmpdir, abspath(cwd))
        assert_equal(tmpdir, abspath(getcwd()))
    with in_dir(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_(isfile(MY_PATH)) 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: sysconfig.py    GNU General Public License v3.0 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 47
Project: Health-Checker   Author: KriAga   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 48
Project: Health-Checker   Author: KriAga   File: sysconfig.py    MIT License 5 votes vote down vote up
def _safe_realpath(path):
    try:
        return realpath(path)
    except OSError:
        return path 
Example 49
Project: neuropredict   Author: raamana   File: io.py    MIT License 5 votes vote down vote up
def get_metadata_in_pyradigm(meta_data_supplied, meta_data_format='pyradigm'):
    "Returns sample IDs and their classes from a given pyradigm"

    meta_data_format = meta_data_format.lower()
    if meta_data_format in ['pyradigm', 'mldataset']:
        dataset = load_dataset(realpath(meta_data_supplied))
    elif meta_data_format in ['arff', 'weka']:
        dataset = load_arff_dataset(realpath(meta_data_supplied))
    else:
        raise NotImplementedError('Meta data format {} not implemented. '
                                  'Only pyradigm and ARFF are supported.'
                                  ''.format(meta_data_format))

    return dataset.samplet_ids, dataset.targets 
Example 50
Project: neuropredict   Author: raamana   File: utils.py    MIT License 5 votes vote down vote up
def check_paths(paths, path_type=''):
    "Converts path to absolute paths and ensures they all exist!"

    abs_paths = list(map(realpath, paths))
    for pp in abs_paths:
        if not pexists(pp):
            raise IOError("One of {} paths specified does not exist:"
                          "\n {}".format(path_type, pp))

    return abs_paths