我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.islink()。
def getCoverPath(): blockList = ['hdd', 'net', 'mmc', 'cf', 'usb', 'upnp', 'sdcard', 'uSDextra'] dirList = os_listdir("/media") coverPaths = ['/usr/share/enigma2/cover/', '/data/cover/', '/media/cf/cover/', '/media/usb/cover/', '/media/upnp/cover/', '/media/sdcard/cover/', '/media/hdd/cover/', '/media/net/cover/', '/media/mmc/cover/', '/media/uSDextra/cover/'] if fileExists("/proc/mounts"): mountsFile = open("/proc/mounts" ,"r") for line in mountsFile: entry = line.split() if entry[2] in ["nfs", "nfs4", "smbfs", "cifs", "djmount"]: if entry[1].startswith("/media/"): blockList.append(entry[1][7:]) mountsFile.close() for dir in dirList: if dir in blockList: print dir, blockList continue if os_path.ismount("/media/%s" %(dir)) or (os_path.islink("/media/%s" %(dir)) and os_path.ismount(os_path.realpath("/media/%s" %(dir)))): path = "/media/%s/cover/" % (dir) coverPaths.append(path) return coverPaths
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
def remove_path(path): """ Remove path. Arguments: path (str): Returns: None """ if islink(path): remove(path) elif isdir(path): rmtree(path) elif exists(path): remove(path)
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'] + (['-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)
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
def walk_directories(root): """'find' in a generator function.""" for child in os.listdir(root): if child.startswith("."): continue full_path = path.join(root, child) if path.isfile(full_path): yield full_path elif full_path.endswith((path.sep+".", path.sep+"..")): continue elif path.islink(full_path): continue else: for fp in walk_directories(full_path): yield fp
def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = join(self.directory, file) if isdir(fullname) and not islink(fullname): self.stack.append(fullname) if fnmatch.fnmatch(file, self.pattern): return fullname ###################################################################### # The real thing ######################################################################
def copy_tree(src: str, dst: str) -> None: if not exists(src): raise FileNotFoundError("Cannot copy non-existent file or directory '{}'.".format(src)) makedirs(dst, exist_ok=True) for content in [join(src, content) for content in listdir(src)]: if islink(content): link_target = readlink(content) link_name = basename(content) symlink(link_target, join(dst, link_name)) elif isdir(content): directory_name = join(dst, basename(content)) makedirs(directory_name, exist_ok=True) copy_tree(content, directory_name) elif isfile(content): copy(content, dst) else: raise UserWarning("unknown file type: {}".format(content))
def run(self): siteMediaDir = op.join(PROJ_ROOT, 'media') if not op.exists(siteMediaDir): os.mkdir(siteMediaDir) subApps = find_sub_apps() for name, directory in subApps: mediaDirectory = op.join(directory, 'media', name) if not op.exists(mediaDirectory): self.announce("skipping " + name + ": media directory does not exist") continue destination = op.join(siteMediaDir, name) if op.exists(destination): if not op.islink(destination): self.announce("skipping " + name + ": not a symlink") continue if not self.force: self.announce("skipping " + name + ": file exists (use -f to override)") continue os.remove(destination) os.symlink(directory, destination)
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)
def rmtree(path, chmod_files='auto', *args, **kwargs): """To remove git-annex .git it is needed to make all files and directories writable again first Parameters ---------- chmod_files : string or bool, optional Either to make files writable also before removal. Usually it is just a matter of directories to have write permissions. If 'auto' it would chmod files on windows by default `*args` : `**kwargs` : Passed into shutil.rmtree call """ # Give W permissions back only to directories, no need to bother with files if chmod_files == 'auto': chmod_files = on_windows if not os.path.islink(path): rotree(path, ro=False, chmod_files=chmod_files) shutil.rmtree(path, *args, **kwargs) else: # just remove the symlink os.unlink(path)
def lmtime(filepath, mtime): """Set mtime for files, while not de-referencing symlinks. To overcome absence of os.lutime Works only on linux and OSX ATM """ from .cmd import Runner # convert mtime to format touch understands [[CC]YY]MMDDhhmm[.SS] smtime = time.strftime("%Y%m%d%H%M.%S", time.localtime(mtime)) lgr.log(3, "Setting mtime for %s to %s == %s", filepath, mtime, smtime) Runner().run(['touch', '-h', '-t', '%s' % smtime, filepath]) rfilepath = realpath(filepath) if islink(filepath) and exists(rfilepath): # trust noone - adjust also of the target file # since it seemed like downloading under OSX (was it using curl?) # didn't bother with timestamps lgr.log(3, "File is a symlink to %s Setting mtime for it to %s", rfilepath, mtime) os.utime(rfilepath, (time.time(), mtime)) # doesn't work on OSX # Runner().run(['touch', '-h', '-d', '@%s' % mtime, filepath])
def test_fresh_clone(env): '''Make a fresh clone and pull''' # make the origin repo make_origin(env) # clone it clone = env.clone(cache_dir='clone_cache') # pull big files (initially soft) check_call(['git', 'big', 'pull']) assert islink(join(clone.repo_dir, 'foo')) assert islink(join(clone.repo_dir, 'bar')) assert not isfile(join(clone.repo_dir, 'foo')) assert not isfile(join(clone.repo_dir, 'bar')) # pull big files (now hard) check_output(['git', 'big', 'pull', '--hard']) assert isfile(join(clone.repo_dir, 'foo')) assert isfile(join(clone.repo_dir, 'bar'))
def dir_size(dir): """ calculate the size of files under a dir based on the os module example""" # It's really hard to give an approximate value for package's # installed size. Gettin a sum of all files' sizes if far from # being true. Using 'du' command (like Debian does) can be a # better solution :(. # Not really, du calculates size on disk, this is much better -- exa from os.path import getsize, islink, isdir, exists join = join_path if exists(dir) and (not isdir(dir) and not islink(dir)): #so, this is not a directory but file.. return getsize(dir) if islink(dir): return long(len(os.readlink(dir))) def sizes(): for root, dirs, files in os.walk(dir): yield sum([getsize(join(root, name)) for name in files if not islink(join(root,name))]) yield sum([long(len(os.readlink((join(root, name))))) for name in files if islink(join(root,name))]) return sum( sizes() )
def testUnpackZip(self): spec = SpecFile("tests/pccts/pspec.xml") targetDir = '/tmp/pisitest' assert spec.source.archive.type == "zip" achv = sourcearchive.SourceArchive(spec, targetDir) achv.fetch(interactive=False) achv.unpack(clean_dir=True) assert pathexists(targetDir + "/pccts") testfile = targetDir + "/pccts/history.txt" assert pathexists(testfile) # check file integrity self.assertEqual(util.sha1_file(testfile), "f2be0f9783e84e98fe4e2b8201a8f506fcc07a4d") # TODO: no link file in pccts package. Need to find a ZIP file # containing a symlink # check for symbolic links # testfile = targetDir + "/sandbox/testdir/link1" # assert islink(testfile)
def _download_wrapped_file(download): download_path = download.abspath # We do not allow symlinks as downloads for security reasons if not path.exists(download_path) or path.islink(download_path): return HttpResponse("Download not found", status=HTTP_NOT_FOUND) wrapper = FileWrapper(open(download_path, "rb")) response = HttpResponse(wrapper, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="{}"'.format( DOWNLOAD_FNAME_TEMLATE.format( filename=path.basename(download_path), download_pk=download.pk, problem_slug=download.problem.slug ) ) response['Content-Length'] = path.getsize(download_path) return response
def _safeCopy(src, dst, overwrite = True): """ Copy a file/dir @params: `src`: The source file `dst`: The destination `overwrite`: Whether overwrite the destination @return: True if succeed else False """ if not path.exists(src): return False if path.exists(dst) and not path.samefile(src, dst) and overwrite: if path.isdir(dst) and not path.islink(dst): rmtree(dst) else: remove(dst) if not path.exists(dst): if path.isdir(src): copytree(src, dst) else: copyfile(src, dst) return True
def Cleanup(delete_dir, delete_threshold, freeup_amount): free_space = FreeSpaceMB(delete_dir) if free_space < delete_threshold: files = [f for f in map(lambda x: join(delete_dir, x), listdir(delete_dir)) \ if isfile(f) and not islink(f)] # Sort files acsending based on their modification time. files.sort(key=lambda f: getmtime(f)) freed = 0.0 # Delete enough files to free up enough space that macthes freeup_amount for f in files: # Size of file in MB f_size = getsize(f) / 1024 / 1024 remove(f) print "Deleted ", f freed = freed + f_size if freed >= freeup_amount: break
def islink(self): st = self.path.lstat() return S_ISLNK(self._osstatresult.st_mode)
def islink(self): return islink(self.strpath)
def islink(path): return False
def islink(self): # We can't use cached stat results here, because that is the stat of # the destination - (see #1773) which in *every case* but this one is # the right thing to use. We could call lstat here and use that, but # it seems unlikely we'd actually save any work that way. -glyph return islink(self.path)
def test_linkstorage(sourcedir, tmpdir): """Test file storage copy.""" fsrc = join(sourcedir, 'simple/package.json') fdst = join(tmpdir, 'simple/package.json') fs = LinkStorage(sourcedir, tmpdir) # File is linked assert not exists(fdst) fs.run() assert exists(fdst) assert islink(fdst) assert realpath(fdst) == realpath(fsrc) # Nothing - file is already linked fs.run() assert exists(fdst) assert islink(fdst) assert realpath(fdst) == realpath(fsrc) # Relink file, and try to copy again (file is relinked) remove(fdst) symlink(__file__, fdst) assert realpath(fdst) != realpath(fsrc) fs.run() assert islink(fdst) assert realpath(fdst) == realpath(fsrc)
def _copyfile(self, src, dst, force=False): """Symlink file from source to destination.""" if exists(dst): if (not islink(dst) or realpath(src) == realpath(dst)) \ and not force: return remove(dst) symlink(src, dst)
def eol_info_from_path_patterns(path_patterns, recursive=False, includes=[], excludes=[]): """Generate EOL info for the given paths. Yields 3-tuples: (PATH, EOL, SUGGESTED-EOL) See eol_info_from_text() docstring for details. """ from os.path import islink assert not isinstance(path_patterns, _BASESTRING), \ "'path_patterns' must be a sequence, not a string: %r" % path_patterns for path in _paths_from_path_patterns(path_patterns, recursive=recursive, includes=includes, excludes=excludes): try: fin = open(path, "rb") except EnvironmentError: _, ex, _ = sys.exc_info() if ex.errno in (errno.ENOENT, errno.EISDIR) and islink(path): log.debug("skipped `%s': symlink" % path) continue raise try: content = fin.read() finally: fin.close() if _BYTES_NULL in content: log.debug("skipped `%s': binary file (null in content)" % path) continue eol, suggested_eol = eol_info_from_text(content) yield path, eol, suggested_eol
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)
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)
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
def _link(src, dst, linktype=LINK_HARD): if linktype == LINK_HARD: if on_win: from ctypes import windll, wintypes CreateHardLink = windll.kernel32.CreateHardLinkW CreateHardLink.restype = wintypes.BOOL CreateHardLink.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPVOID] if not CreateHardLink(dst, src, None): raise OSError('win32 hard link failed') else: os.link(src, dst) elif linktype == LINK_COPY: # copy relative symlinks as symlinks if islink(src) and not os.readlink(src).startswith(os.path.sep): os.symlink(os.readlink(src), dst) else: shutil.copy2(src, dst) else: raise Exception("Did not expect linktype=%r" % linktype)
def rm_rf(path): """ try to delete path, but never fail """ try: if islink(path) or isfile(path): # Note that we have to check if the destination is a link because # exists('/path/to/dead-link') will return False, although # islink('/path/to/dead-link') is True. os.unlink(path) elif isdir(path): shutil.rmtree(path) except (OSError, IOError): pass
def walk(top, topdown=True, followlinks=False): """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
def _receive(self, root, directory, dirs, files, include, exclude): """Internal function processing each yield from os.walk.""" self._received += 1 if not self.symlinks: where = root + path.sep + directory + path.sep files = [ file_name for file_name in files if not path.islink(where + file_name) ] include = FileSetState("Include", directory, include, None if include else self.include) exclude = FileSetState("Exclude", directory, exclude, None if exclude else self.exclude) if exclude.matches_all_files_all_subdirs(): # Exclude everything and do no traverse any subdirectories del dirs[0:] matched = set() else: if include.no_possible_matches_in_subdirs(): # Do no traverse any subdirectories del dirs[0:] matched = include.match(set(files)) matched -= exclude.match(matched) return matched, include, exclude
def run(self): subModules = find_submodules() for name, directory in subModules: destination = op.join(PROJ_ROOT, name) if op.exists(destination): if not op.islink(destination): self.announce("skipping " + name + ": not a symlink") continue if not self.force: self.announce("skipping " + name + ": file exists (use -f to override)") continue os.remove(destination) os.symlink(directory, destination)
def setup_env(t, opts): """Set up the environment for the test.""" # symlinks links = opts['links'] for link in links: frm = links[link] to = join(t, link) debug("Symlinking {0} to {1}".format(frm, to)) if islink(to): os.unlink(to) os.symlink(frm, to)
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)
def walk(top, topdown=True, onerror=None): from os import error, listdir from os.path import join, isdir, islink # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.path.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: path = join(top, name) if not islink(path): for x in walk(path, topdown, onerror): yield x if not topdown: yield top, dirs, nondirs