Python os.path.islink() Examples

The following are 30 code examples for showing how to use os.path.islink(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: cloudify-manager-blueprints   Author: cloudify-cosmo   File: create.py    License: Apache License 2.0 6 votes vote down vote up
def _configure_dbus(rest_venv):
    # link dbus-python-1.1.1-9.el7.x86_64 to the venv for `cfy status`
    # (module in pypi is very old)
    site_packages = 'lib64/python2.7/site-packages'
    dbus_relative_path = join(site_packages, 'dbus')
    dbuslib = join('/usr', dbus_relative_path)
    dbus_glib_bindings = join('/usr', site_packages, '_dbus_glib_bindings.so')
    dbus_bindings = join('/usr', site_packages, '_dbus_bindings.so')
    if isdir(dbuslib):
        dbus_venv_path = join(rest_venv, dbus_relative_path)
        if not islink(dbus_venv_path):
            utils.ln(source=dbuslib, target=dbus_venv_path, params='-sf')
            utils.ln(source=dbus_bindings, target=dbus_venv_path, params='-sf')
        if not islink(join(rest_venv, site_packages)):
            utils.ln(source=dbus_glib_bindings, target=join(
                    rest_venv, site_packages), params='-sf')
    else:
        ctx.logger.warn(
                'Could not find dbus install, cfy status will not work') 
Example 2
Project: igcollect   Author: innogames   File: linux_network.py    License: MIT License 6 votes vote down vote up
def get_interfaces(self):
        for dev in listdir(self._scn):
            dev_path = join(self._scn, dev)
            if not (islink(dev_path) or isdir(dev_path)):
                # Skip regular files
                continue
            if not self.included_types:
                # Send metrics for all devices
                self.netdev_stat[dev] = {}
                continue
            for i_type in self.included_types:
                checks = self.NET_TYPES[i_type]
                results = []
                for check, arg in zip(checks[::2], checks[1::2]):
                    results.append(check(self, dev, arg))
                if False not in results:
                    self.netdev_stat[dev] = {} 
Example 3
Project: pipeline   Author: liorbenhorin   File: plat_other.py    License: MIT License 6 votes vote down vote up
def find_ext_volume_global_trash(volume_root):
    # from [2] Trash directories (1) check for a .Trash dir with the right
    # permissions set.
    trash_dir = op.join(volume_root, TOPDIR_TRASH)
    if not op.exists(trash_dir):
        return None
    
    mode = os.lstat(trash_dir).st_mode
    # vol/.Trash must be a directory, cannot be a symlink, and must have the
    # sticky bit set.
    if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
        return None

    trash_dir = op.join(trash_dir, str(uid))
    try:
        check_create(trash_dir)
    except OSError:
        return None
    return trash_dir 
Example 4
Project: fbs   Author: mherrmann   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def clean():
    """
    Remove previous build outputs
    """
    try:
        rmtree(path('target'))
    except FileNotFoundError:
        return
    except OSError:
        # In a docker container, target/ may be mounted so we can't delete it.
        # Delete its contents instead:
        for f in listdir(path('target')):
            fpath = join(path('target'), f)
            if isdir(fpath):
                rmtree(fpath, ignore_errors=True)
            elif isfile(fpath):
                remove(fpath)
            elif islink(fpath):
                unlink(fpath) 
Example 5
Project: ibeis   Author: Erotemic   File: _thesis_helpers.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, dbname=None):
        self.ibs = None
        self.expt_results = {}
        if isdir(dbname) or islink(dbname):
            dpath = abspath(dbname)
        else:
            dpath = None

        self.dbname = dbname
        self.dname = None
        self.dpath = dpath
        self.species_nice = dbname_to_species_nice(dbname)

        if self.dpath is None and dbname is not None:
            self.dname = self.dbname

            link_dname = ut.get_argval('--link', default='link')
            self.dpath = join(self.base_dpath, link_dname, self.dname) 
Example 6
Project: nfi   Author: georgenicolaou   File: ApplicationParser.py    License: GNU General Public License v3.0 6 votes vote down vote up
def scan_single_app_dir(self, dirroot, app, dirobject, store_app):
        for f in listdir(dirroot):
            filepath = join(dirroot,f)
            if isdir(filepath): 
                subdirobject = dirobject.add_dir(f)
                self.scan_single_app_dir(filepath, app, subdirobject, store_app)
            elif islink(filepath):
                """Skip for now"""
                continue
            elif isfile(filepath):
                try:
                    dirobject.add_file(self.handle_file(f, dirroot, app))
                    store_app.totalfiles += 1
                except:
                    print("Error handling file %(fname)s" % {'fname': join(dirroot,f)})
        return 
Example 7
Project: nfi   Author: georgenicolaou   File: ApplicationParser.py    License: GNU General Public License v3.0 6 votes vote down vote up
def scan_single_app(self, approot_path, app):
        #print "[APP]: " + app.get_packagename()
        if self.outqueue != None:
            self.outqueue.put("[APP]: " + app.get_packagename())
        store_app = self.exstore.create_application(
                                app.get_packagename(), app.get_canonicalname())
        rootdir = store_app.add_directory(approot_path)
        store_app.add_root_stats( os.stat(approot_path) )
        for f in listdir(approot_path):
            filepath = join(approot_path,f)
            if isdir(filepath):
                dirobject = rootdir.add_dir(f)
                self.scan_single_app_dir(filepath, app, dirobject, store_app)
            elif islink(filepath):
                if filepath.endswith("lib"):
                    store_app.set_library_path(self.read_link(filepath))
            elif isfile(filepath):
                store_app.totalfiles += 1
                rootdir.add_file(self.handle_file(f,approot_path,app))
        return 
Example 8
Project: clonedigger   Author: jlachowski   File: fileutils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def remove_dead_links(directory, verbose=0):
    """recursivly traverse directory and remove all dead links

    :type directory: str
    :param directory: directory to cleanup

    :type verbose: bool
    :param verbose:
      flag indicating wether information about deleted links should be
      printed to stderr, default to False
    """
    def _remove_dead_link(_, directory, fnames):
        """walk handler"""
        for filename in fnames:
            src = join(directory, filename)
            if islink(src) and not exists(src):
                if verbose:
                    print('remove dead link', src)
                remove(src)
    walk(directory, _remove_dead_link, None) 
Example 9
Project: walle-web   Author: meolu   File: repo.py    License: Apache License 2.0 6 votes vote down vote up
def is_git_dir(self):
        '''
        判断是否为git目录

        @param path:
        @return:
        '''
        d = self.path + '/.git'
        if osp.isdir(d):
            if osp.isdir(osp.join(d, 'objects')) and osp.isdir(osp.join(d, 'refs')):
                headref = osp.join(d, 'HEAD')
                return osp.isfile(headref) or \
                       (osp.islink(headref) and
                        os.readlink(headref).startswith('refs'))
            elif (osp.isfile(osp.join(d, 'gitdir')) and
                  osp.isfile(osp.join(d, 'commondir')) and
                  osp.isfile(osp.join(d, 'gitfile'))):
                return False
        return False 
Example 10
Project: Snu-Photo-Manager   Author: snuq   File: plat_other.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_ext_volume_global_trash(volume_root):
    # from [2] Trash directories (1) check for a .Trash dir with the right
    # permissions set.
    trash_dir = op.join(volume_root, TOPDIR_TRASH)
    if not op.exists(trash_dir):
        return None

    mode = os.lstat(trash_dir).st_mode
    # vol/.Trash must be a directory, cannot be a symlink, and must have the
    # sticky bit set.
    if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
        return None

    trash_dir = op.join(trash_dir, text_type(uid).encode('ascii'))
    try:
        check_create(trash_dir)
    except OSError:
        return None
    return trash_dir 
Example 11
Project: FileManager   Author: math2001   File: plat_other.py    License: MIT License 6 votes vote down vote up
def find_ext_volume_global_trash(volume_root):
    # from [2] Trash directories (1) check for a .Trash dir with the right
    # permissions set.
    trash_dir = op.join(volume_root, TOPDIR_TRASH)
    if not op.exists(trash_dir):
        return None

    mode = os.lstat(trash_dir).st_mode
    # vol/.Trash must be a directory, cannot be a symlink, and must have the
    # sticky bit set.
    if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
        return None

    trash_dir = op.join(trash_dir, text_type(uid).encode('ascii'))
    try:
        check_create(trash_dir)
    except OSError:
        return None
    return trash_dir 
Example 12
Project: Splunking-Crime   Author: nccgroup   File: install.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _link(src, dst, linktype=LINK_HARD):
    if linktype == LINK_HARD:
        if on_win:
            win_hard_link(src, dst)
        else:
            os.link(src, dst)
    elif linktype == LINK_SOFT:
        if on_win:
            win_soft_link(src, dst)
        else:
            os.symlink(src, dst)
    elif linktype == LINK_COPY:
        # copy relative symlinks as symlinks
        if not on_win and islink(src) and not os.readlink(src).startswith('/'):
            os.symlink(os.readlink(src), dst)
        else:
            shutil.copy2(src, dst)
    else:
        raise Exception("Did not expect linktype=%r" % linktype) 
Example 13
Project: pyrqlite   Author: rqlite   File: setup.py    License: MIT License 6 votes vote down vote up
def run(self):
        testpath = 'src/test'
        buildlink = 'build/lib/test'

        if isdir(dirname(buildlink)):
            if islink(buildlink):
                os.unlink(buildlink)

            os.symlink(relpath(testpath, dirname(buildlink)), buildlink)
            testpath = buildlink

        try:
            os.environ['EPYTHON'] = 'python{}.{}'.format(sys.version_info.major, sys.version_info.minor)
            subprocess.check_call(['py.test', '-v', testpath, '-s',
                        '--cov-report=html', '--cov-report=term-missing'] +
                       (['-k', self.match] if self.match else []) +
                       ['--cov={}'.format(p) for p in find_packages(dirname(testpath), exclude=['test'])])

        finally:
            if islink(buildlink):
                os.unlink(buildlink) 
Example 14
Project: macke   Author: tum-i22   File: helper.py    License: Apache License 2.0 6 votes vote down vote up
def get_fuzz_outdirs(macke_directory):
    fuzzdir = path.join(macke_directory, "fuzzer")
    if not path.isdir(path.join(macke_directory, "fuzzer")):
        return []

    result = []
    prefix = "fuzz_out_"

    for f in listdir(fuzzdir):
        if not f.startswith(prefix):
            continue
        fpath = path.join(fuzzdir, f)
        function = f[len(prefix):]
        if path.islink(fpath) or not path.isdir(fpath):
            continue
        result.append((function, fpath))

    return result 
Example 15
Project: bazarr   Author: morpheus65535   File: fun.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_git_dir(d):
    """ This is taken from the git setup.c:is_git_directory
    function.

    @throws WorkTreeRepositoryUnsupported if it sees a worktree directory. It's quite hacky to do that here,
            but at least clearly indicates that we don't support it.
            There is the unlikely danger to throw if we see directories which just look like a worktree dir,
            but are none."""
    if osp.isdir(d):
        if osp.isdir(osp.join(d, 'objects')) and osp.isdir(osp.join(d, 'refs')):
            headref = osp.join(d, 'HEAD')
            return osp.isfile(headref) or \
                (osp.islink(headref) and
                 os.readlink(headref).startswith('refs'))
        elif (osp.isfile(osp.join(d, 'gitdir')) and
              osp.isfile(osp.join(d, 'commondir')) and
              osp.isfile(osp.join(d, 'gitfile'))):
            raise WorkTreeRepositoryUnsupported(d)
    return False 
Example 16
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 17
Project: py   Author: pytest-dev   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 18
Project: py   Author: pytest-dev   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 19
Project: platform   Author: syncloud   File: hardware.py    License: GNU General Public License v3.0 5 votes vote down vote up
def relink_disk(link, target):

    os.chmod(target, 0o755)

    if islink(link):
        unlink(link)
    os.symlink(target, link) 
Example 20
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 21
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 22
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 23
Project: python-netsurv   Author: sofia-netsurv   File: local.py    License: MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 24
Project: igcollect   Author: innogames   File: linux_network.py    License: MIT License 5 votes vote down vote up
def _check_symlink(self, dev, symlink):
        return islink(join(self._scn, dev, symlink)) 
Example 25
Project: PyPPL   Author: pwwang   File: channel.py    License: Apache License 2.0 5 votes vote down vote up
def fromPattern(pattern, ftype='any', sortby='name', reverse=False):
        """@API
        Create a Channel from a path pattern
        @params:
            pattern (str): the pattern with wild cards
            ftype (str): the type of the files/dirs to include
              - 'dir', 'file', 'link' or 'any' (default)
            sortby (str):  how the list is sorted
              - 'name' (default), 'mtime', 'size'
            reverse (bool): reverse sort. Default: `False`
        @returns:
            (Channel): The Channel created from the path
        """
        if sortby == 'name':
            key = str
        elif sortby == 'mtime':
            key = path.getmtime
        elif sortby == 'size':
            key = path.getsize

        filt = lambda afile: True
        if ftype == 'link':
            filt = path.islink
        elif ftype == 'dir':
            filt = lambda afile: path.isdir(afile) and not path.islink(afile)
        elif ftype == 'file':
            filt = lambda afile: path.isfile(afile) and not path.islink(afile)
        files = [afile for afile in glob(str(pattern)) if filt(afile)]
        return Channel.create(sorted(files, key=key, reverse=reverse)) 
Example 26
Project: nautilus-folder-icons   Author: bilelmoussaoui   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_pixbuf(theme, icon_name):
    pixbuf = None
    try:
        icon_info = theme.lookup_icon(icon_name, 64, 0)
        if not icon_info.is_symbolic():
            icon_path = icon_info.get_filename()
            if not path.islink(icon_path) and icon_name.startswith("folder"):
                pixbuf = icon_info.load_icon()
    except GLib.Error:
        pixbuf = theme.load_icon("image-missing", 64, 0)
    if pixbuf and (pixbuf.props.width != 64 or pixbuf.props.height != 64):
        pixbuf = pixbuf.scale_simple(64, 64,
                                     GdkPixbuf.InterpType.BILINEAR)
    return pixbuf 
Example 27
Project: clonedigger   Author: jlachowski   File: shellutils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rm(*files):
    """a shell like rm, supporting wildcards
    """
    for wfile in files:
        for filename in glob.glob(wfile):
            if islink(filename):
                os.remove(filename)
            elif isdir(filename):
                shutil.rmtree(filename)
            else:
                os.remove(filename) 
Example 28
Project: scylla   Author: acaceres2176   File: local.py    License: Apache License 2.0 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 29
Project: scylla   Author: acaceres2176   File: local.py    License: Apache License 2.0 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 30
Project: ubelt   Author: Erotemic   File: test_links.py    License: Apache License 2.0 5 votes vote down vote up
def test_broken_link():
    """
    CommandLine:
        python -m ubelt.tests.test_links test_broken_link
    """
    dpath = ub.ensure_app_cache_dir('ubelt', 'test_broken_link')

    ub.delete(dpath, verbose=2)
    ub.ensuredir(dpath, verbose=2)
    util_links._dirstats(dpath)

    broken_fpath = join(dpath, 'broken_fpath.txt')
    broken_flink = join(dpath, 'broken_flink.txt')

    ub.touch(broken_fpath, verbose=2)
    util_links._dirstats(dpath)
    ub.symlink(broken_fpath, broken_flink, verbose=2)

    util_links._dirstats(dpath)
    ub.delete(broken_fpath, verbose=2)

    util_links._dirstats(dpath)

    # make sure I am sane that this is the correct check.
    can_symlink = util_links._can_symlink()
    print('can_symlink = {!r}'.format(can_symlink))
    if can_symlink:
        # normal behavior
        assert islink(broken_flink)
        assert not exists(broken_flink)
    else:
        # on windows hard links are essentially the same file.
        # there is no trace that it was actually a link.
        assert exists(broken_flink)