def test_islink(self): self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) f = open(test_support.TESTFN + "1", "wb") try: f.write("foo") f.close() self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) if hasattr(os, "symlink"): os.symlink(test_support.TESTFN + "1", test_support.TESTFN + "2") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) os.remove(test_support.TESTFN + "1") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) self.assertIs(posixpath.exists(test_support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(test_support.TESTFN + "2"), True) finally: if not f.close(): f.close() try: os.remove(test_support.TESTFN + "1") except os.error: pass try: os.remove(test_support.TESTFN + "2") except os.error: pass self.assertRaises(TypeError, posixpath.islink)
def test_islink(self): self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) f = open(test_support.TESTFN + "1", "wb") try: f.write("foo") f.close() self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) if hasattr(os, "symlink"): os.symlink(test_support.TESTFN + "1", test_support.TESTFN + "2") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) os.remove(test_support.TESTFN + "1") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) self.assertIs(posixpath.exists(test_support.TESTFN + "2"), False) finally: if not f.close(): f.close() try: os.remove(test_support.TESTFN + "1") except os.error: pass try: os.remove(test_support.TESTFN + "2") except os.error: pass self.assertRaises(TypeError, posixpath.islink)
def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), False) f = open(support.TESTFN + "1", "wb") try: f.write(b"foo") f.close() self.assertIs(posixpath.islink(support.TESTFN + "1"), False) finally: if not f.close(): f.close()
def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), False) with open(support.TESTFN + "1", "wb") as f: f.write(b"foo") self.assertIs(posixpath.islink(support.TESTFN + "1"), False) if support.can_symlink(): os.symlink(support.TESTFN + "1", support.TESTFN + "2") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) os.remove(support.TESTFN + "1") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) self.assertIs(posixpath.exists(support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), True)
def swap_dir(rootpath, path): """Swap a symlink with its target directory. Args: rootpath: Rootpath for tag conversions. path: Path of target symlink. """ target = path if posixpath.islink(target) and posixpath.isdir(target): here = target there = pathlib.readlink(target) # here is the symlink # there is the dir here_tag = tagnames.path2tag(rootpath, here) there_tag = tagnames.path2tag(rootpath, there) dtags.remove_tag(here, here_tag) dtags.add_tag(here, there_tag) os.unlink(here) # here is now nothing # there is now the dir os.rename(there, here) # here is now the dir # there is now nothing os.symlink(here, there) else: raise ValueError('{} is not a symlink to a directory'.format(target))
def getnameversion(filename): """ Read the alias and version number from a """ """ CA distribution .info file """ if posixpath.islink(filename): return ["","",""] caname = "" version = "" sha1fp0 = "" try: inf = open(filename,'r') except: print "__status 3 Missing CA info file %s."%filename sys.exit(3) for line in inf: if re.match('^alias.*',line): (junk, caname, _) = re.split(r'^alias\s*=\s*(.*)', line) #print caname if re.match('^version.*',line): (junk, version, _) = re.split(r'version\s*=\s*([0-9]+.[0-9]+)', line) #print version if re.match("^sha1fp\.0",line): (junk, sha1fp0, _) = re.split(r'sha1fp\.0\s*=\s*([0-9A-F:]{59})', line) #print sha1fp0 if ((caname != "") and (version != "")): return [caname,version,sha1fp0] return ["","",""]
def getAttributes(self, path): attributes = {} sys_path = "/sys%s" % path try: names = os.listdir(sys_path) except OSError: return attributes for name in names: name_path = posixpath.join(sys_path, name) if name[0] == "." \ or name in ["dev", "uevent"] \ or posixpath.isdir(name_path) \ or posixpath.islink(name_path): continue try: value = open(name_path, "r").read().strip() except IOError: continue value = value.split("\n")[0] if [c for c in value if not isprint(c)]: continue attributes[name] = value return attributes
def generate(filename, str): if type(str) != type(''): raise GenerateOnlyTakesStrings, type(str) happy = 0 if posixpath.islink(filename): print '(Blowing away symlink ' + filename + ' to make way for autogenerated file)' os.remove(filename) try: o = open(filename, 'r') snow = o.read() o.close() if snow == str: happy = 1 except: # it is not there; pass pass if not happy: try: o = open(filename, 'w') o.write(str) o.close() except: print 'Error: Unable to generate ' + filename sys.exit(1) else: #print '(No changes to '+filename+')' pass
def generate(filename, str): if type(str) != type(''): raise GenerateOnlyTakesStrings, type(str) happy = 0 if posixpath.islink(filename): print '(Blowing away symlink '+filename+' to make way for autogenerated file)' os.remove(filename) try: o = open(filename, 'r') snow = o.read() o.close() if snow == str: happy = 1 except: # it is not there; pass pass if not happy: try: o = open(filename, 'w') o.write(str) o.close() except: print 'Error: Unable to generate '+filename sys.exit(1) else: #print '(No changes to '+filename+')' pass
def clean_symlinks(dirpath): """Remove all broken symlinks under the given directory.""" # Broken symlinks appear as files, so we skip directories. for dirpath, _, filenames in os.walk(dirpath): for filename in filenames: path = posixpath.join(dirpath, filename) if posixpath.islink(path) and not posixpath.exists(path): os.unlink(path)
def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) f = open(support.TESTFN + "1", "wb") try: f.write(b"foo") f.close() self.assertIs(posixpath.islink(support.TESTFN + "1"), False) if support.can_symlink(): os.symlink(support.TESTFN + "1", support.TESTFN + "2") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) os.remove(support.TESTFN + "1") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) self.assertIs(posixpath.exists(support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), True) finally: if not f.close(): f.close()
def test_islink(self): self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) f = open(test_support.TESTFN + "1", "wb") try: f.write("foo") f.close() self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) if hasattr(os, 'symlink'): os.symlink(test_support.TESTFN + "1", test_support.TESTFN + "2") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) os.remove(test_support.TESTFN + "1") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) self.assertIs(posixpath.exists(test_support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(test_support.TESTFN + "2"), True) finally: if not f.close(): f.close()
def test_swap_dir(self): with patch('dantalian.dtags.add_tag', autospec=True) as mock_add, \ patch('dantalian.dtags.remove_tag', autospec=True) as mock_rm: base.swap_dir(self.root, 'bag/apple') self.assertTrue(posixpath.islink('apple')) self.assertTrue(posixpath.isdir('bag/apple')) mock_rm.assert_called_with('bag/apple', '//bag/apple') mock_add.assert_called_with('bag/apple', '//apple')
def bus(self): sys_path = posixpath.join( "/sys%s" % self._environment["DEVPATH"], "subsystem") if posixpath.islink(sys_path): link = os.readlink(sys_path) if "/" in link: return posixpath.basename(link) return None
def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + "1"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), False) f = open(support.TESTFN + "1", "wb") try: f.write(b"foo") f.close() self.assertIs(posixpath.islink(support.TESTFN + "1"), False) if support.can_symlink(): os.symlink(support.TESTFN + "1", support.TESTFN + "2") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) os.remove(support.TESTFN + "1") self.assertIs(posixpath.islink(support.TESTFN + "2"), True) self.assertIs(posixpath.exists(support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(support.TESTFN + "2"), True) finally: if not f.close(): f.close()
def test_islink(self): self.assertIs(posixpath.islink(support.TESTFN + '1'), False) self.assertIs(posixpath.lexists(support.TESTFN + '2'), False) f = open(support.TESTFN + '1', 'wb') try: f.write(b'foo') f.close() self.assertIs(posixpath.islink(support.TESTFN + '1'), False) if support.can_symlink(): os.symlink(support.TESTFN + '1', support.TESTFN + '2') self.assertIs(posixpath.islink(support.TESTFN + '2'), True) os.remove(support.TESTFN + '1') self.assertIs(posixpath.islink(support.TESTFN + '2'), True) self.assertIs(posixpath.exists(support.TESTFN + '2'), False) self.assertIs(posixpath.lexists(support.TESTFN + '2'), True) finally: if not f.close(): f.close()
def unlink(rootpath, path): """Unlink given path. If the target is a directory without any other links, raise OSError. """ target = path # We unlink the target. However, if it is a directory, we want to swap it # out for one of its symlinks, then unlink the symlink. If the directory # doesn't have any tags, then we fail. if posixpath.isdir(target): if not posixpath.islink(target): tags = dtags.list_tags(target) if not tags: raise oserrors.is_a_directory(target) swap_candidate = tagnames.tag2path(rootpath, tags[0]) swap_dir(rootpath, swap_candidate) assert posixpath.islink(target) dtags.remove_tag(target, tagnames.path2tag(rootpath, target)) os.unlink(target)
def test_islink(self): self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) f = open(test_support.TESTFN + "1", "org.eclipse.wb") try: f.write("foo") f.close() self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False) if hasattr(os, "symlink"): os.symlink(test_support.TESTFN + "1", test_support.TESTFN + "2") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) os.remove(test_support.TESTFN + "1") self.assertIs(posixpath.islink(test_support.TESTFN + "2"), True) self.assertIs(posixpath.exists(test_support.TESTFN + "2"), False) self.assertIs(posixpath.lexists(test_support.TESTFN + "2"), True) finally: if not f.close(): f.close()
def canonicalize(canon, subpath, linkcache={}, verbose=0): if verbose: print canon, ' -> [', subpath, ']' # split the subpath in to components pathsplit = string.split(subpath, '/') # if we haven't got any, then we get returned [''] if len(pathsplit) == 1 and pathsplit[0] == '': return canon # make linksrc the thing under consideration; ie the top element of subpath linksrc = canon + '/' + pathsplit[0] # define the variable linkdest to be None if linksrc is not a link, # else make it be the place that linksrc is pointing to if linkcache.has_key(linksrc): linkdest = linkcache[linksrc] else: linkdest = None if posixpath.islink(linksrc): linkdest = os.readlink(linksrc) linkcache[linksrc] = linkdest if linkdest: # linksrc is a link, deal with it if linkdest[0] == '/': # we have found an absolute link # so restart the resolution, using linkdest as our subpath if verbose: print 'abslink', linkdest return canonicalize( '', linkdest[1:] + '/' + string.join(pathsplit[1:], '/'), linkcache, verbose) else: # we have found a relative link # peel off any .. by stripping away canon while linkdest[0:2] == '../': if verbose: print 'uplink', linkdest canon = string.join(string.split(canon, '/')[:-1], '/') linkdest = linkdest[3:] if verbose: print 'rellink', linkdest # recurse with the new (possible reduced) canon and the stripped down path return canonicalize( canon, linkdest + '/' + string.join(pathsplit[1:], '/'), linkcache, verbose) else: # we take this branch if the linksrc was absolute, or it did not exist if verbose: print 'abs ', pathsplit[0] return canonicalize(canon + '/' + pathsplit[0], string.join(pathsplit[1:], '/'), linkcache, verbose)
def file_exists(file_name, type='file'): if len(file_name) == 0: return 0 else: if exists(file_name): if type == 'file' and isfile(file_name): return 1 elif type == 'dir' and isdir(file_name): return 1 else: if islink(file_name): print "INFO: using '%s' which is a link" % file_name return 1 else: return 0 else: return 0
def file_exists(file_name, type = 'file'): if len(file_name) == 0: return 0 else: if exists(file_name): if type == 'file' and isfile(file_name): return 1 elif type == 'dir' and isdir(file_name): return 1 else: if islink(file_name): print "INFO: using '%s' which is a link" % file_name return 1 else: return 0 else: return 0
def canonicalize(canon, subpath, linkcache = {}, verbose=0): if verbose: print canon, ' -> [',subpath,']' # split the subpath in to components pathsplit = string.split(subpath, '/') # if we haven't got any, then we get returned [''] if len(pathsplit) == 1 and pathsplit[0] == '': return canon # make linksrc the thing under consideration; ie the top element of subpath linksrc = canon + '/' + pathsplit[0] # define the variable linkdest to be None if linksrc is not a link, # else make it be the place that linksrc is pointing to if linkcache.has_key(linksrc): linkdest = linkcache[linksrc] else: linkdest = None if posixpath.islink(linksrc): linkdest = os.readlink(linksrc) linkcache[linksrc] = linkdest if linkdest: # linksrc is a link, deal with it if linkdest[0] == '/': # we have found an absolute link # so restart the resolution, using linkdest as our subpath if verbose: print 'abslink',linkdest return canonicalize('', linkdest[1:] + '/' + string.join(pathsplit[1:], '/'), linkcache, verbose) else: # we have found a relative link # peel off any .. by stripping away canon while linkdest[0:2] == '../': if verbose: print 'uplink',linkdest canon = string.join(string.split(canon, '/')[:-1], '/') linkdest = linkdest[3:] if verbose: print 'rellink',linkdest # recurse with the new (possible reduced) canon and the stripped down path return canonicalize(canon, linkdest + '/' + string.join(pathsplit[1:], '/'), linkcache, verbose) else: # we take this branch if the linksrc was absolute, or it did not exist if verbose: print 'abs ',pathsplit[0] return canonicalize(canon + '/' + pathsplit[0], string.join(pathsplit[1:], '/'), linkcache, verbose)
def test_islink(self): self.assertIs(posixpath.islink(os_helper.TESTFN + "1"), False) self.assertIs(posixpath.lexists(os_helper.TESTFN + "2"), False) with open(os_helper.TESTFN + "1", "wb") as f: f.write(b"foo") self.assertIs(posixpath.islink(os_helper.TESTFN + "1"), False) if os_helper.can_symlink(): os.symlink(os_helper.TESTFN + "1", os_helper.TESTFN + "2") self.assertIs(posixpath.islink(os_helper.TESTFN + "2"), True) os.remove(os_helper.TESTFN + "1") self.assertIs(posixpath.islink(os_helper.TESTFN + "2"), True) self.assertIs(posixpath.exists(os_helper.TESTFN + "2"), False) self.assertIs(posixpath.lexists(os_helper.TESTFN + "2"), True) self.assertIs(posixpath.islink(os_helper.TESTFN + "\udfff"), False) self.assertIs(posixpath.islink(os.fsencode(os_helper.TESTFN) + b"\xff"), False) self.assertIs(posixpath.islink(os_helper.TESTFN + "\x00"), False) self.assertIs(posixpath.islink(os.fsencode(os_helper.TESTFN) + b"\x00"), False)
def readlink(path): """Follow all symlinks and return the target of the last link.""" while posixpath.islink(path): path = os.readlink(path) return path
def is_symlink(self): return path.islink(self.path)
def walk(top, topdown=True, onerror=None, followlinks=False): """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. By default errors from the os.scandir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end="") print(sum([getsize(join(root, name)) for name in files]), end="") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ top = fspath(top) dirs = [] nondirs = [] walk_dirs = [] # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.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 scandir is global in this module due # to earlier import-*. scandir_it = scandir(top) except OSError as error: if onerror is not None: onerror(error) return with scandir_it: while True: try: try: entry = next(scandir_it) except StopIteration: break except OSError as error: if onerror is not None: onerror(error) return try: is_dir = entry.is_dir() except OSError: # If is_dir() raises an OSError, consider that the entry is not # a directory, same behaviour than os.path.isdir(). is_dir = False if is_dir: dirs.append(entry.name) else: nondirs.append(entry.name) if not topdown and is_dir: # Bottom-up: recurse into sub-directory, but exclude symlinks to # directories if followlinks is False if followlinks: walk_into = True else: try: is_symlink = path.islink(entry.path) except OSError: # If is_symlink() raises an OSError, consider that the # entry is not a symbolic link, same behaviour than # os.path.islink(). is_symlink = False walk_into = not is_symlink if walk_into: walk_dirs.append(entry.path) # Yield before recursion if going top down if topdown: yield top, dirs, nondirs # Recurse into sub-directories islink, join = path.islink, path.join for dirname in dirs: new_path = join(top, dirname) # Issue #23605: os.path.islink() is used instead of caching # entry.is_symlink() result during the loop on os.scandir() because # the caller can replace the directory entry during the "yield" # above. if followlinks or not islink(new_path): yield from walk(new_path, topdown, onerror, followlinks) else: yield new_path, None, None else: # Recurse into sub-directories for new_path in walk_dirs: yield from walk(new_path, topdown, onerror, followlinks) # Yield after recursion if going bottom up yield top, dirs, nondirs
if item.get_name() == 'boot_images_'+treeinfo.target_name: instname = 'image' if item.get_class() in ['program', 'posixprogram', 'module']: instname = item.get_binary_object_name() if item.get_make_flag('donotinstall'): instname = '' if instname != '': if item.options['value'] == 2: mapping[instname] = item.get_path() else: forbidden.append(instname) if item.get_make_flag('install'): for instname in item.get_make_flag('install'): mapping[instname] = item.get_path() print 'Omitting ',forbidden print 'Linking ',len(mapping.keys()) files = os.listdir('.') for file in files: if posixpath.islink(file) and file != 'Makefile' and (file in forbidden or file in mapping.keys()): os.unlink(file) for file in mapping.keys(): install(buildpath, mapping[file], file) print
def proc_get_open_fds(pid=None): """Try really, really hard to get a process's open file descriptors""" pid = pid or os.getpid() fd_dir = '/proc/{}/fd'.format(pid) try: # Try /proc on Linux first try: os.scandir except AttributeError: # Python < 3.5 return [ int(fd) for fd in os.listdir(fd_dir) if posixpath.islink(posixpath.join(fd_dir, fd)) ] else: # Python >= 3.5 return [ int(e.name) for e in os.scandir(fd_dir) if os.readlink(e.path) != fd_dir ] except OSError as e: if e.errno != errno.ENOENT: raise DaemonEnvironmentError( 'Unable to get open file descriptors using "/proc/<pid>/fd" ' '({error})'.format(error=str(e))) # We're not on Linux (maybe macOS?) try: # Try getting FDs from lsof cmd = ['lsof', '-a', '-d0-8192', '-p', str(pid)] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # We'll obviously need to exclude these below exclude_fds = {p.stdout.fileno(), p.stderr.fileno()} stdout, stderr = p.communicate() if p.returncode != 0 or not stdout.strip(): raise subprocess.CalledProcessError(returncode=p.returncode, cmd=cmd, output=stdout + stderr) except Exception as e: # lsof failed for some reason. If this is the current process, # try to find any FDs up to 8192 (to be somewhat conservative). # If it's not the current process, just fail. if pid != os.getpid(): raise DaemonEnvironmentError( 'Unable to get open file descriptors using "lsof" ' '({error})'.format(error=str(e))) fds = [] for fd in range(8192): try: os.fstat(fd) except OSError as e: if e.errno == errno.EBADF: # Bad file descriptor continue raise else: fds.append(fd) return fds else: # Parse the output of lsof lines = [line.strip() for line in stdout.strip().split(b'\n')] # Find which field contains the FD field_names = [f.lower() for f in _re_whitespace.split(lines[0])] fd_field_index = field_names.index(b'fd') fds = [] for line in lines[1:]: fields = [f.lower() for f in _re_whitespace.split(line)] # Strip out non-digit characters and convert to int fd = int(_re_non_digits.sub(b'', fields[fd_field_index])) if fd in exclude_fds: continue fds.append(fd) return fds
if item.get_name() == 'boot_images_' + treeinfo.target_name: instname = 'image' if item.get_class() in ['program', 'posixprogram', 'module']: instname = item.get_binary_object_name() if item.get_make_flag('donotinstall'): instname = '' if instname != '': if item.options['value'] == 2: mapping[instname] = item.get_path() else: forbidden.append(instname) if item.get_make_flag('install'): for instname in item.get_make_flag('install'): mapping[instname] = item.get_path() print 'Omitting ', forbidden print 'Linking ', len(mapping.keys()) files = os.listdir('.') for file in files: if posixpath.islink(file) and file != 'Makefile' and ( file in forbidden or file in mapping.keys()): os.unlink(file) for file in mapping.keys(): install(buildpath, mapping[file], file) print
def update_event(self, inp=-1): self.set_output_val(0, posixpath.islink(self.input(0)))