def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" try: posix.stat(path) except posix.error: return False return True
def test_stat_unicode(self): # test that passing unicode would not raise UnicodeDecodeError import posix try: posix.stat(u"ą") except OSError: pass
def exists(path): """Local re-implementation of os.path.exists.""" try: stat(path) except EnvironmentError: return False return True
def dir_exists(f): try: posix.stat(f) return 1 except posix.error, (a, b): if (a != 2): raise sys.exc_type, sys.exc_value, sys.exc_traceback return 0
def exists(path): """Local re-implementation of os.path.exists.""" try: stat(path) except EnvironmentError, e: # TODO: how to get the errno under RPython? if not __rpython__: if e.errno not in (errno.ENOENT, errno.ENOTDIR, errno.ESRCH): raise return False
def cmp(f1, f2): # Compare two files, use the cache if possible. # Return 1 for identical files, 0 for different. # Raise exceptions if either file could not be statted, read, etc. s1, s2 = sig(posix.stat(f1)), sig(posix.stat(f2)) if s1[0] <> 8 or s2[0] <> 8: # Either is a not a plain file -- always report as different return 0 if s1 = s2: # type, size & mtime match -- report same return 1
def exists(path): """Local re-implementation of os.path.exists.""" try: stat(path) except EnvironmentError, e: # TODO: how to get the errno under RPython? if not __rpython__: if e.errno not in (errno.ENOENT,errno.ENOTDIR,errno.ESRCH,): raise return False
def exists(path): """Local re-implementation of os.path.exists.""" try: stat(path) except EnvironmentError: e = sys.exc_info()[1] if e.errno not in (errno.ENOENT,errno.ENOTDIR,errno.ESRCH,): raise else: return False else: return True
def ismount(path): try: s1 = posix.stat(path) s2 = posix.stat(join(path, '..')) except posix.error: return 0 # It doesn't exist -- so not a mount point :-) dev1 = s1[stat.ST_DEV] dev2 = s2[stat.ST_DEV] if dev1 != dev2: return 1 # path/.. on a different device as path ino1 = s1[stat.ST_INO] ino2 = s2[stat.ST_INO] if ino1 == ino2: return 1 # path/.. is the same i-node as path return 0
def isdir(s): """Return true if the pathname refers to an existing directory.""" try: st = posix.stat(s) except posix.error: return False return stat.S_ISDIR(st.st_mode)
def which(program): """Like /bin/csh's which command. Takes a program name as an argument, and searches the PATH environment variable for the specified program. If found, the full path to program is returned, otherwise None is returned.""" # first figure out which PATH we're going to search try: path = os.environ['PATH'] except KeyError: path = os.defpath # split the path import string import posix import stat pathdirs = string.splitfields(path, os.pathsep) found_p = None for dir in pathdirs: try: found_p = os.path.join(dir, program) st = posix.stat(found_p) # check for both a regular file, and executable by owner if not stat.S_ISREG(st[stat.ST_MODE]) or \ not (stat.S_IMODE(st[stat.ST_MODE]) & stat.S_IXUSR): # nope found_p = None except posix.error: found_p = None # if a path was found, we're done if found_p: return found_p # never found return None
def files(request, publication_id): publication = get_object_or_404(Publication, pk=publication_id) filepath = publication.file.__unicode__() name, ext = splitext(filepath) filepath_absolute = join(settings.MEDIA_ROOT, filepath) if not exists(filepath_absolute): raise Http404 statinfo = stat(filepath_absolute) mimetype = mimetypes.guess_type(filepath_absolute) mode = getattr(settings, 'PUBLICATIONS_DOWNLOAD_MODE', '') if mode == 'apache': response = HttpResponse(content_type=mimetype) response['X-Sendfile'] = smart_str(filepath_absolute) if mode == 'nginx': response = HttpResponse(content_type=mimetype) response['X-Accel-Redirect'] = smart_str(settings.MEDIA_URL + filepath) else: response = HttpResponse(open(filepath_absolute, "r"), content_type=mimetype) response['Content-Length'] = statinfo.st_size response['Content-Disposition'] = 'attachment; filename=%s%s' % (smart_str(publication.generate_identifier()), ext) response['Cache-Control'] = 'no-cache, must-revalidate' return response
def Matches(self, comp): """ TODO: Cache is never cleared. - When we get a newer timestamp, we should clear the old one. - When PATH is changed, we can remove old entries. """ val = self.mem.GetVar('PATH') if val.tag != value_e.Str: # No matches if not a string return path_dirs = val.s.split(':') #print(path_dirs) names = [] for d in path_dirs: try: st = posix.stat(d) except OSError as e: # There could be a directory that doesn't exist in the $PATH. continue key = (d, st.st_mtime) listing = self.cache.get(key) if listing is None: listing = posix.listdir(d) self.cache[key] = listing names.extend(listing) # TODO: Shouldn't do the prefix / space thing ourselves. readline does # that at the END of the line. for word in listing: if word.startswith(comp.to_complete): yield word + ' '
def test_posix_stat_result(self): try: import posix except ImportError: return expect = posix.stat(__file__) encoded = jsonpickle.encode(expect) actual = jsonpickle.decode(encoded) self.assertEqual(expect, actual)
def readable(path): try: mode = posix.stat(path)[stat.ST_MODE] except OSError: # File doesn't exist sys.stderr.write("%s not found\n"%path) sys.exit(1) if not stat.S_ISREG(mode): # or it's not readable sys.stderr.write("%s not readable\n"%path) sys.exit(1)
def test_posix_stat_result(): """Serialize a posix.stat() result""" try: import posix except ImportError: return expect = posix.stat(__file__) encoded = jsonpickle.encode(expect) actual = jsonpickle.decode(encoded) assert expect == actual
def skipfile(file): if file in badnames or \ badprefix(file) or badsuffix(file) or \ path.islink(file) or path.isdir(file): return 1 # Skip huge files -- probably binaries. try: st = posix.stat(file) except posix.error: return 1 # Doesn't exist -- skip it return st[stat.ST_SIZE] >= MAXSIZE
def readfile(fn): st = posix.stat(fn) size = st[stat.ST_SIZE] if not size: return '' try: fp = open(fn, 'r') except: raise posix.error, 'readfile(' + fn + '): open failed' try: return fp.read(size) except: raise posix.error, 'readfile(' + fn + '): read failed'
def mkrealdir(name): st = posix.stat(name) # Get the mode mode = S_IMODE(st[ST_MODE]) linkto = posix.readlink(name) files = posix.listdir(name) posix.unlink(name) posix.mkdir(name, mode) posix.chmod(name, mode) linkto = cat('..', linkto) # for file in files: if file not in ('.', '..'): posix.symlink(cat(linkto, file), cat(name, file))
def mkrealfile(name): st = posix.stat(name) # Get the mode mode = S_IMODE(st[ST_MODE]) linkto = posix.readlink(name) # Make sure again it's a symlink f_in = open(name, 'r') # This ensures it's a file posix.unlink(name) f_out = open(name, 'w') while 1: buf = f_in.read(BUFSIZE) if not buf: break f_out.write(buf) del f_out # Flush data to disk before changing mode posix.chmod(name, mode)
def tun_tap_available(tap_only=0, probe_only=0): if sys.platform[:5] == "sunos": if tap_only: msg = "Solaris does not support TAP, only TUN." return tun_tap_error(msg, 0, probe_only) # TODO: msg = "No TUN support for Solaris yet." return tun_tap_error(msg, 0, probe_only) elif sys.platform[:5] == "linux": device_name = "/dev/net/tun" else: # TODO: actually check if the TAP driver is installed return 1 # msg = "Simics does not support TUN/TAP on %s." % sys.platform # return tun_tap_error(msg, 0, probe_only) try: posix.stat(device_name) have_tun = 1 try: fd = open(device_name, "rw") fd.close() tun_ok = 1 except: tun_ok = 0 except: have_tun = 0 if have_tun == 0: msg = "TUN/TAP not supported on this host. (No %s found)." % device_name return tun_tap_error(msg, 1, probe_only) elif tun_ok == 0: msg = ("TUN/TAP device not accessible. (Check permissions of the " + "%s device file.)" % device_name) return tun_tap_error(msg, 1, probe_only) return 1
def listdir(path): # List directory contents, using cache try: cached_mtime, list = cache[path] del cache[path] except RuntimeError: cached_mtime, list = -1, [] try: mtime = posix.stat(path)[8] except posix.error: return [] if mtime <> cached_mtime: try: list = posix.listdir(path) except posix.error: return [] list.sort() cache[path] = mtime, list return list
def Matches(self, comp): """ TODO: Cache is never cleared. - When we get a newer timestamp, we should clear the old one. - When PATH is changed, we can remove old entries. """ val = self.mem.GetVar('PATH') if val.tag != value_e.Str: # No matches if not a string return path_dirs = val.s.split(':') #log('path: %s', path_dirs) executables = [] for d in path_dirs: try: st = posix.stat(d) except OSError as e: # There could be a directory that doesn't exist in the $PATH. continue key = (d, st.st_mtime) dir_exes = self.cache.get(key) if dir_exes is None: entries = posix.listdir(d) dir_exes = [] for name in entries: path = os_path.join(d, name) # TODO: Handle exception if file gets deleted in between listing and # check? if not posix.access(path, posix.X_OK): continue dir_exes.append(name) # append the name, not the path self.cache[key] = dir_exes executables.extend(dir_exes) # TODO: Shouldn't do the prefix / space thing ourselves. readline does # that at the END of the line. for word in executables: if word.startswith(comp.to_complete): yield word
import posix mask = 0o170000 mask2 = 0o777 S_IFDIR = 0o40000 S_IFREG = 0o100000 S_IFLNK = 0o120000 sr = posix.stat("programs/files/stat") assert sr.st_mode & mask == S_IFREG assert sr.st_mode & mask2 == 0o664 assert sr.st_dev == 0x815 assert sr.st_ino.__class__ is int assert sr.st_nlink.__class__ is int assert sr.st_uid == 1003 assert sr.st_gid == 1003 assert sr.st_size == 4 assert int(sr.st_atime) >= 1372977779, sr.st_atime assert int(sr.st_mtime) >= 1366755120, sr.st_mtime assert sr.st_ctime.__class__ is float sr2 = posix.stat("programs/files/stat2") assert sr2.st_mode & mask == S_IFDIR sr3 = posix.stat("programs/files/stat3", follow_symlinks=False) assert sr3.st_mode & mask == S_IFLNK sr3 = posix.stat("programs/files/stat3") assert sr3.st_mode & mask == S_IFDIR
import posix import errno try: posix.stat("programs/files/filenotfound") except FileNotFoundError as e: assert e.errno == errno.ENOENT try: posix.stat("programs/files/stat4/somefile") except PermissionError as e: assert e.errno == errno.EACCES try: posix.stat("programs/files/stat/somefile") except NotADirectoryError as e: assert e.errno == errno.ENOTDIR try: posix.stat("programs/files/" + "stat3/" * 100) except OSError as e: assert e.__class__ is OSError assert e.errno == errno.ELOOP try: posix.stat("programs/files/" * 1000) except OSError as e: assert e.__class__ is OSError assert e.errno == errno.ENAMETOOLONG x = 5 assert x == 5
def isdir(path): try: st = posix.stat(path) except posix.error: return 0 return stat.S_ISDIR(st[stat.ST_MODE])
def exists(path): try: st = posix.stat(path) except posix.error: return 0 return 1
def isfile(path): try: st = posix.stat(path) except posix.error: return 0 return stat.S_ISREG(st[stat.ST_MODE])
def do_stat(self, path): if not path: path = self._work_dir print posix.stat(path)
import sys import rpyc from plumbum import SshMachine from rpyc.utils.zerodeploy import DeployedServer from rpyc.utils.splitbrain import splitbrain mach = SshMachine("192.168.1.117") print sys.platform with DeployedServer(mach) as dep: conn = dep.classic_connect() print conn.modules.sys.platform try: import posix except ImportError as ex: print ex with splitbrain(conn): import posix print posix.stat("/boot") print posix
def samefile(f1, f2): s1 = posix.stat(f1) s2 = posix.stat(f2) return samestat(s1, s2)
def copystat(src, dst): st = posix.stat(src) mode = divmod(st[0], MODEBITS)[1] posix.chmod(dst, mode) posix.utimes(dst, st[7:9])
def Eval(self, node): #print('!!', node.tag) if node.tag == bool_expr_e.WordTest: s = self._EvalCompoundWord(node.w) return bool(s) if node.tag == bool_expr_e.LogicalNot: b = self.Eval(node.child) return not b if node.tag == bool_expr_e.LogicalAnd: # Short-circuit evaluation if self.Eval(node.left): return self.Eval(node.right) else: return False if node.tag == bool_expr_e.LogicalOr: if self.Eval(node.left): return True else: return self.Eval(node.right) if node.tag == bool_expr_e.BoolUnary: op_id = node.op_id s = self._EvalCompoundWord(node.child) # Now dispatch on arg type arg_type = BOOL_ARG_TYPES[op_id] # could be static in the LST? if arg_type == bool_arg_type_e.Path: # Only use lstat if we're testing for a symlink. if op_id in (Id.BoolUnary_h, Id.BoolUnary_L): try: mode = posix.lstat(s).st_mode except OSError: return False return stat.S_ISLNK(mode) try: mode = posix.stat(s).st_mode except OSError: # TODO: Signal extra debug information? #log("Error from stat(%r): %s" % (s, e)) return False if op_id in (Id.BoolUnary_e, Id.BoolUnary_a): # -a is alias for -e return True if op_id == Id.BoolUnary_f: return stat.S_ISREG(mode) if op_id == Id.BoolUnary_d: return stat.S_ISDIR(mode) if op_id == Id.BoolUnary_x: return posix.access(s, posix.X_OK) if op_id == Id.BoolUnary_r: return posix.access(s, posix.R_OK) if op_id == Id.BoolUnary_w: return posix.access(s, posix.W_OK) raise NotImplementedError(op_id) if arg_type == bool_arg_type_e.Str: if op_id == Id.BoolUnary_z: return not bool(s) if op_id == Id.BoolUnary_n: return bool(s) raise NotImplementedError(op_id) if arg_type == bool_arg_type_e.Other: if op_id == Id.BoolUnary_t: try: fd = int(s) except ValueError: # TODO: Need location information of [ e_die('Invalid file descriptor %r', s) return posix.isatty(fd) raise NotImplementedError(op_id) raise NotImplementedError(arg_type) if node.tag == bool_expr_e.BoolBinary: op_id = node.op_id s1 = self._EvalCompoundWord(node.left) # Whether to glob escape do_fnmatch = op_id in (Id.BoolBinary_GlobEqual, Id.BoolBinary_GlobDEqual, Id.BoolBinary_GlobNEqual) do_ere = (op_id == Id.BoolBinary_EqualTilde) s2 = self._EvalCompoundWord(node.right, do_fnmatch=do_fnmatch, do_ere=do_ere) # Now dispatch on arg type arg_type = BOOL_ARG_TYPES[op_id] if arg_type == bool_arg_type_e.Path: st1 = posix.stat(s1) st2 = posix.stat(s2) # TODO: test newer than (mtime) if op_id == Id.BoolBinary_nt: return st1[stat.ST_MTIME] > st2[stat.ST_MTIME] if op_id == Id.BoolBinary_ot: return st1[stat.ST_MTIME] < st2[stat.ST_MTIME] raise NotImplementedError(op_id) if arg_type == bool_arg_type_e.Int: # NOTE: We assume they are constants like [[ 3 -eq 3 ]]. # Bash also allows [[ 1+2 -eq 3 ]]. i1 = self._StringToIntegerOrError(s1, blame_word=node.left) i2 = self._StringToIntegerOrError(s2, blame_word=node.right) if op_id == Id.BoolBinary_eq: return i1 == i2 if op_id == Id.BoolBinary_ne: return i1 != i2 if op_id == Id.BoolBinary_gt: return i1 > i2 if op_id == Id.BoolBinary_ge: return i1 >= i2 if op_id == Id.BoolBinary_lt: return i1 < i2 if op_id == Id.BoolBinary_le: return i1 <= i2 raise NotImplementedError(op_id) if arg_type == bool_arg_type_e.Str: if op_id in (Id.BoolBinary_GlobEqual, Id.BoolBinary_GlobDEqual): #log('Matching %s against pattern %s', s1, s2) # TODO: Respect extended glob? * and ! and ? are quoted improperly. # But @ and + are OK. return libc.fnmatch(s2, s1) if op_id == Id.BoolBinary_GlobNEqual: return not libc.fnmatch(s2, s1) if op_id in (Id.BoolBinary_Equal, Id.BoolBinary_DEqual): return s1 == s2 if op_id == Id.BoolBinary_NEqual: return s1 != s2 if op_id == Id.BoolBinary_EqualTilde: #log('Matching %r against regex %r', s1, s2) try: matches = libc.regex_match(s2, s1) except RuntimeError: # 2 means a parse error. Note this is a fatal error in OSH but not # in bash. e_die("Invalid regex %r", s2, word=node.right, status=2) if matches is None: return False self._SetRegexMatches(matches) return True if op_id == Id.Redir_Less: # pun return s1 < s2 if op_id == Id.Redir_Great: # pun return s1 > s2 raise NotImplementedError(op_id) raise AssertionError(node.tag)
def stat(path): if cache.has_key(path): return cache[path] cache[path] = ret = posix.stat(path) return ret
import posix import sys # read the contents of this file fd = posix.open(__file__, posix.O_RDONLY) data = posix.read(fd, 1024) posix.close(fd) print('the file\'s read size is %d bytes' % len(data)) # check that the file's stat shows the correct size st = posix.stat(__file__) print('the file\'s stat size is %d bytes' % st.st_size)
def test_stat(self): if hasattr(posix, 'stat'): self.assert_(posix.stat(test_support.TESTFN))
import posix for file in posix.listdir("."): print file, posix.stat(file)[6] ## aifc-example-1.py 314 ## anydbm-example-1.py 259 ## array-example-1.py 48
def Method1(): global code user_id = getUserID(input('# Type your user login ID : ')) for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: code = 'Continue' break if code == 'Continue': print('# Any process belonged to typed user is found.') while True: option = input( '# Do you want to send signal to these processes for closing? (Y/N) : ' ) if option in ['Y', 'N']: break if option == 'N': code = 'Cancelled' return else: print('# Retriving processes list...') pids = [] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: pids.append(int(entry)) print('# Quitting processes...') if posix.getuid() != user_id and posix.getuid() != 0: print( '# Error : Don\'t have enough permission. Make sure to run this troubleshooter as root.' ) code = 'RequiredRoot' return for pid in pids: posix.kill(pid, 15) input( 'Waiting for processes to be closed properly (Recommended at 20 seconds). When ready then press enter.' ) print('# Retriving processes list...') pids = [] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: pids.append(int(entry)) if pids: while True: option = input( '# There are processes not quitted by the signal. Do you want to force killing it? (Y/N) : ' ) if option in ['Y', 'N']: break if option == 'N': code = 'Cancelled' return print('# Killing processes...') for pid in pids: posix.kill(pid, 9) code = 'Complete' return else: print('# No any process belonged to typed user is found.') code = 'NoSolution' return
def copymode(src, dst): st = posix.stat(src) mode = divmod(st[0], MODEBITS)[1] posix.chmod(dst, mode)