Python os.path.islink() Examples

The following are code examples for showing how to use os.path.islink(). 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: 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 2
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 3
Project: igcollect   Author: innogames   File: linux_network.py    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 4
Project: pipeline   Author: liorbenhorin   File: plat_other.py    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 5
Project: useful-scripts   Author: opencoff   File: rm.py    GNU General Public License v2.0 6 votes vote down vote up
def main(argv):

    if len(argv) == 1 or argv[1] == '-h':
        print "Usage: %s FILE [FILE..]" % argv[0]
        sys.exit(1)

    for f in argv[1:]:
        if not isfile(f) and not islink(f):
            continue

        s = "%-50s [y/N]? " % f
        r = prompt(s)
        if r < 0:
            sys.exit(0)

        elif r > 0:
            os.unlink(f) 
Example 6
Project: fbs   Author: mherrmann   File: __init__.py    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 7
Project: conf   Author: XonqNopp   File: fileutils.py    GNU General Public License v3.0 6 votes vote down vote up
def remove_dead_links(directory, verbose=0):
    """Recursively traverse directory and remove all dead links.

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

    :type verbose: bool
    :param verbose:
      flag indicating whether information about deleted links should be
      printed to stderr, default to False
    """
    for dirpath, dirname, filenames in walk(directory):
        for filename in dirnames + filenames:
            src = join(dirpath, filename)
            if islink(src) and not exists(src):
                if verbose:
                    print('remove dead link', src)
                remove(src) 
Example 8
Project: conf   Author: XonqNopp   File: fileutils.py    GNU General Public License v3.0 6 votes vote down vote up
def remove_dead_links(directory, verbose=0):
    """Recursively traverse directory and remove all dead links.

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

    :type verbose: bool
    :param verbose:
      flag indicating whether information about deleted links should be
      printed to stderr, default to False
    """
    for dirpath, dirname, filenames in walk(directory):
        for filename in dirnames + filenames:
            src = join(dirpath, filename)
            if islink(src) and not exists(src):
                if verbose:
                    print('remove dead link', src)
                remove(src) 
Example 9
Project: bowerer   Author: idlesign   File: project.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gather_installed_links(self):
        components_path = join(self.config['cwd'], self.config['directory'])

        endpoints = {}

        for directory in listdir(components_path):
            fullpath = join(components_path, directory)

            if not (isdir(fullpath) and islink(fullpath)):
                continue

            pkg_meta, deprecated, _ = read_json(fullpath, dummy_json={'name': directory})
            pkg_meta['_direct'] = True
            endpoints[directory] = {
                'name': directory,
                'source': fullpath,
                'target': '*',
                'canonicalDir': fullpath,
                'pkgMeta': pkg_meta,
                'linked': True
            }
        return endpoints 
Example 10
Project: tcnc   Author: utlco   File: devlinks.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def create_symlink(pathname, symlink_pathname):
    """
    Args:
        pathname: Pathname of file to create a symbolic link to
        symlink_pathname: Name of symbolic link
    """
    # If the symbolic link already exists or a file
    # of the same name exists then remove it.
    if path.exists(symlink_pathname):
        if not path.islink(symlink_pathname):
            query_str = 'Remove existing file %s?' % symlink_pathname
            # If the symlink pathname is an actual file then
            # get confirmation from user to delete it.
            if not query_yesno(query_str):
                print 'Not creating link to ' + pathname
                return
        try:
            print 'Removing ' + symlink_pathname
            os.remove(symlink_pathname)
        except OSError, error:
            print error
            exit(-1)
    # Create a symbolic link to the pathname. 
Example 11
Project: FMICodeGenerator   Author: ghorwin   File: plat_other.py    BSD 3-Clause "New" or "Revised" 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: crates   Author: naggie   File: crawler.py    MIT License 6 votes vote down vote up
def process_task(self,filepath):
        # what sort of file is it? Guess the model to use from extension.
        root, ext = splitext(filepath)

        if islink(filepath):
            raise TaskSkipped('Linked file is probably mapped to CAS')

        #if not access(filepath,R_OK):
        #    raise TaskError('Could not access %s' % filepath)

        if ext == '.mp3':
            AudioFile.from_mp3(filepath).save()

        elif ext == '.aac':
            AudioFile.from_aac(filepath).save()
        else:
            raise TaskSkipped('Not a supported file %s' % filepath)


# TODO: ask the cas if it has the ref first 
Example 13
Project: snpPipeline   Author: kanzwataru   File: plat_other.py    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))
    try:
        check_create(trash_dir)
    except OSError:
        return None
    return trash_dir 
Example 14
Project: sqlalchemy-rqlite   Author: rqlite   File: setup.py    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,
                        '--cov-report=html', '--cov-report=term'] +
                       (['-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 15
Project: walle-web   Author: meolu   File: repo.py    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 16
Project: node-gn   Author: Shouqun   File: fileutils.py    MIT License 6 votes vote down vote up
def remove_dead_links(directory, verbose=0):
    """Recursively traverse directory and remove all dead links.

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

    :type verbose: bool
    :param verbose:
      flag indicating whether information about deleted links should be
      printed to stderr, default to False
    """
    for dirpath, dirname, filenames in walk(directory):
        for filename in dirnames + filenames:
            src = join(dirpath, filename)
            if islink(src) and not exists(src):
                if verbose:
                    print('remove dead link', src)
                remove(src) 
Example 17
Project: Snu-Photo-Manager   Author: snuq   File: plat_other.py    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 18
Project: FileManager   Author: math2001   File: plat_other.py    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 19
Project: Splunking-Crime   Author: nccgroup   File: install.py    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 20
Project: Taigabot   Author: FrozenPigs   File: fun.py    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 21
Project: pyrqlite   Author: rqlite   File: setup.py    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 22
Project: inplace   Author: jwodder   File: test_symlinks.py    MIT License 6 votes vote down vote up
def test_symlink_nobackup(tmpdir):
    assert pylistdir(tmpdir) == []
    realdir = tmpdir.mkdir('real')
    real = realdir.join('realfile.txt')
    real.write(TEXT)
    linkdir = tmpdir.mkdir('link')
    link = linkdir.join('linkfile.txt')
    symlink('../real/realfile.txt', str(link))
    with InPlace(str(link)) as fp:
        for line in fp:
            fp.write(line.swapcase())
    assert pylistdir(realdir) == ['realfile.txt']
    assert pylistdir(linkdir) == ['linkfile.txt']
    assert islink(str(link))
    assert link.readlink() == '../real/realfile.txt'
    assert link.read() == TEXT.swapcase()
    assert real.read() == TEXT.swapcase() 
Example 23
Project: rpm2swidtag   Author: swidtags   File: swidtags.py    Apache License 2.0 5 votes vote down vote up
def purge_generated_symlink(self):
		symlink_path = path.join(self.swidtags_d, self.generated_dirname)
		if not path.islink(symlink_path):
			return
		self.remove_file(symlink_path) 
Example 24
Project: rpm2swidtag   Author: swidtags   File: swidtags.py    Apache License 2.0 5 votes vote down vote up
def create_swidtags_d_symlink(self, basename=None):
		if basename:
			target = path.join(SWIDTAG_DIR_DOWNLOAD, basename)
		else:
			basename = self.generated_dirname
			target = path.join(SWIDTAG_DIR_GEN, basename)
		if not path.isdir(self.swidtags_d):
			makedirs(self.swidtags_d)
		src = path.join(self.swidtags_d, basename)
		if not path.islink(src):
			symlink(path.join("../../..", target), src) 
Example 25
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedSetup.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def keySave(self):
        # Einstellungen speichern
        if self["config"].isChanged():
            for x in self["config"].list:
                x[1].save()

            chdir(self.skin_base_dir)

            if path.exists(self.font_file):
                remove(self.font_file)
            elif path.islink(self.font_file):
                remove(self.font_file)
            if self.myFont.value != 'default':
                symlink(self.myFont.value, self.font_file)

            if path.exists(self.color_file):
                remove(self.color_file)
            elif path.islink(self.color_file):
                remove(self.color_file)
            if self.myColorScheme.value != 'default':
                symlink(self.myColorScheme.value, self.color_file)

            self.restartGUI()
        elif(self.skinParts_changed):
            self.restartGUI()
        else:
            self.close() 
Example 26
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def needsUpdate(self, newestInput):
        sup = super(LayoutDistribution, self).needsUpdate(newestInput)
        if sup:
            return sup
        for destination, source in self._walk_layout():
            source_type = source['source_type']
            if source_type == 'file':
                for source_file in glob.iglob(join(self.suite.dir, source['path'])):
                    up = _needsUpdate(source_file, self.path)
                    if up:
                        return up
                    if islink(source_file):
                        source_file = join(dirname(source_file), os.readlink(source_file))
                        up = _needsUpdate(source_file, self.path)
                        if up:
                            return up
                    elif isdir(source_file):
                        for root, _, files in os.walk(source_file):
                            up = _needsUpdate(root, self.path)
                            if up:
                                return up
                            for f in files:
                                up = _needsUpdate(join(root, f), self.path)
                                if up:
                                    return up
            elif source_type == 'link':
                pass  # this is handled by _persist_layout
            elif source_type == 'string':
                pass  # this is handled by _persist_layout
            elif source_type in ('dependency', 'extracted-dependency', 'skip'):
                pass  # this is handled by a build task dependency
            else:
                abort("Unsupported source type: '{}' in '{}'".format(source_type, destination), context=suite)
        if not self._check_persisted_layout():
            return "layout definition has changed"
        if not self._check_linky_state():
            return "LINKY_LAYOUT has changed"
        return None 
Example 27
Project: py   Author: pytest-dev   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 28
Project: py   Author: pytest-dev   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 29
Project: Alexa-Ecovacs   Author: EtienneMD   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 30
Project: Alexa-Ecovacs   Author: EtienneMD   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 31
Project: platform   Author: syncloud   File: hardware.py    GNU General Public License v3.0 5 votes vote down vote up
def relink_disk(link, target):

    os.chmod(target, 0755)

    if islink(link):
        unlink(link)
    os.symlink(target, link) 
Example 32
Project: python-netsurv   Author: sofia-netsurv   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 33
Project: python-netsurv   Author: sofia-netsurv   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 34
Project: python-netsurv   Author: sofia-netsurv   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 35
Project: python-netsurv   Author: sofia-netsurv   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 36
Project: rpython-lang-scheme   Author: tomoh1r   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        st = self.path.lstat()
        return S_ISLNK(self._osstatresult.st_mode) 
Example 37
Project: rpython-lang-scheme   Author: tomoh1r   File: local.py    MIT License 5 votes vote down vote up
def islink(self):
        return islink(self.strpath) 
Example 38
Project: igcollect   Author: innogames   File: linux_network.py    MIT License 5 votes vote down vote up
def _check_symlink(self, dev, symlink):
        return islink(join(self._scn, dev, symlink)) 
Example 39
Project: wrfxpy   Author: openwfm   File: utils.py    MIT License 5 votes vote down vote up
def cache_file(path, cache_dir):
    """
    Move file at the path to cache directory and replace by symlink
    except when it is symlink to the cache direcory already
    except if the file is symlink to elsewhere, copy the file to cache directory and replace by symlink

    :path: file name
    :param cache_dir: source directory, must be absolute path
    """
    if not osp.isdir(cache_dir):
        logging.error('%s is not directory' % str(cache_dir))
        raise Exception('%s is not directory' % str(cache_dir))
    if not osp.isfile(path):
        logging.error('%s is not file' % str(path))
        raise Exception('%s is not directory' % str(cache_dir))
    dst = osp.join(cache_dir,osp.basename(path))
    if osp.islink(path):
        if osp.dirname(osp.realpath(path)) is osp.realpath(cache_dir):
            logging.debug('%s is link to %s already' % (path, cache_dir))
            if osp.basename(osp.realpath(path)) is not osp.basename(path):
                logging.error('link %s -> %s does not match' % (path,osp.realpath(path)))
                raise Exception('link %s -> %s does not match' % (path,osp.realpath(path)))
        else:
            src = osp.realpath(path)
            logging.info('Copying %s to %s' % (src, dst))
            shutil.copyfile(src,dst)
    else:
        logging.info('Moving %s to %s' % (path, dst))
        shutil.move(path,dst)
    symlink_unless_exists(dst, path) 
Example 40
Project: omnic   Author: michaelpb   File: test_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def test_recursive_symlinks(self):
        filesystem.recursive_symlink_dirs(self.dir, self.out)

        # Now use walk to check that we did it successfully
        results = set(filesystem.directory_walk(self.out, self.out))
        assert len(results) == len(self.results)  # ensure right number
        for path, _ in results:
            assert islink(path) 
Example 41
Project: omnic   Author: michaelpb   File: test_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def test_recursive_hardlinks(self):
        filesystem.recursive_hardlink_dirs(self.dir, self.out)

        # Now use walk to check that we did it successfully
        results = set(filesystem.directory_walk(self.out, self.out))
        assert len(results) == len(self.results)  # ensure right number
        for path, _ in results:
            assert not islink(path)  # ensure hardlinks 
Example 42
Project: conf   Author: XonqNopp   File: shellutils.py    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 43
Project: conf   Author: XonqNopp   File: shellutils.py    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 44
Project: PyPPL   Author: pwwang   File: channel.py    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 45
Project: tcnc   Author: utlco   File: devlinks.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def confirm_remove_nonsymlink(filepath):
    remove_path = True
    if path.exists(filepath) and not path.islink(filepath):
        # If the file exists and is not a symbolic link then
        # confirm removal.
        remove_path = query_yesno('Remove existing file %s?' % filepath)
    return remove_path 
Example 46
Project: nautilus-folder-icons   Author: bilelmoussaoui   File: utils.py    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 47
Project: Rovers   Author: RIT-Space-Exploration   File: osutil.py    MIT License 5 votes vote down vote up
def walk(top, topdown=True, followlinks=False):
    # type: (unicode, bool, bool) -> Iterator[Tuple[unicode, List[unicode], List[unicode]]]
    """Backport of os.walk from 2.6, where the *followlinks* argument was
    added.
    """
    names = os.listdir(top)

    dirs, nondirs = [], []
    for name in names:
        try:
            fullpath = path.join(top, name)
        except UnicodeError:
            print('%s:: ERROR: non-ASCII filename not supported on this '
                  'filesystem encoding %r, skipped.' % (name, fs_encoding),
                  file=sys.stderr)
            continue
        if path.isdir(fullpath):
            dirs.append(name)
        else:
            nondirs.append(name)

    if topdown:
        yield top, dirs, nondirs
    for name in dirs:
        fullpath = path.join(top, name)
        if followlinks or not path.islink(fullpath):
            for x in walk(fullpath, topdown, followlinks):
                yield x
    if not topdown:
        yield top, dirs, nondirs 
Example 48
Project: urban-journey   Author: urbanjourney   File: rm.py    MIT License 5 votes vote down vote up
def rm(path):
    """Deletes a file, directory or symlink."""
    if exists(path):
        if isdir(path):
            if islink(path):
                unlink(path)
            else:
                rmtree(path)
        else:
            if islink(path):
                unlink(path)
            else:
                remove(path) 
Example 49
Project: crates   Author: naggie   File: cas.py    MIT License 5 votes vote down vote up
def link_out(self,ref,destination):
        '''create an absolute symlink in a path pointing to a ref. If the
        directory tree does not exist, it will be created'''
        binpath = self.select(ref)

        destination_dir = dirname(destination)

        if not isdir(destination_dir):
            makedirs( dirname(destination) )

        if islink(destination) and readlink(destination) == binpath:
            # Don't cause a client read-error if this is an update map
            return

        self._symlink(binpath,destination) 
Example 50
Project: crates   Author: naggie   File: map.py    MIT License 5 votes vote down vote up
def handle(self, *args, **options):
        basedir = options['directories'][0]

        cas = BasicCAS()

        for audioFile in AudioFile.objects.all():
            destination = join(basedir, audioFile.map() )

            # probably upgrade or is the same
            if islink(destination): unlink(destination)

            print destination
            cas.link_out(audioFile.ref,destination)