def getsize(self):
st = self.statinfo
if not st:
self.restat()
st = self.statinfo
return st[ST_SIZE]
python类ST_SIZE的实例源码
def fileSize(file):
"""I'll try my damndest to determine the size of this file object.
"""
size = None
if hasattr(file, "fileno"):
fileno = file.fileno()
try:
stat_ = os.fstat(fileno)
size = stat_[stat.ST_SIZE]
except:
pass
else:
return size
if hasattr(file, "name") and path.exists(file.name):
try:
size = path.getsize(file.name)
except:
pass
else:
return size
if hasattr(file, "seek") and hasattr(file, "tell"):
try:
try:
file.seek(0, 2)
size = file.tell()
finally:
file.seek(0, 0)
except:
pass
else:
return size
return size
def listMessages(self, i=None):
"""Return a list of lengths of all files in new/ and cur/
"""
if i is None:
ret = []
for mess in self.list:
if mess:
ret.append(os.stat(mess)[stat.ST_SIZE])
else:
ret.append(0)
return ret
return self.list[i] and os.stat(self.list[i])[stat.ST_SIZE] or 0
def GenerateFrozenResource(rc_name, output_name, h_name = None):
"""Converts an .rc windows resource source file into a python source file
with the same basic public interface as the rest of this module.
Particularly useful for py2exe or other 'freeze' type solutions,
where a frozen .py file can be used inplace of a real .rc file.
"""
rcp = Parse(rc_name, h_name)
in_stat = os.stat(rc_name)
out = open(output_name, "wt")
out.write("#%s\n" % output_name)
out.write("#This is a generated file. Please edit %s instead.\n" % rc_name)
out.write("__version__=%r\n" % __version__)
out.write("_rc_size_=%d\n_rc_mtime_=%d\n" % (in_stat[stat.ST_SIZE], in_stat[stat.ST_MTIME]))
out.write("class StringDef:\n")
out.write("\tdef __init__(self, id, idNum, value):\n")
out.write("\t\tself.id = id\n")
out.write("\t\tself.idNum = idNum\n")
out.write("\t\tself.value = value\n")
out.write("\tdef __repr__(self):\n")
out.write("\t\treturn \"StringDef(%r, %r, %r)\" % (self.id, self.idNum, self.value)\n")
out.write("class FakeParser:\n")
for name in "dialogs", "ids", "names", "bitmaps", "icons", "stringTable":
out.write("\t%s = \\\n" % (name,))
pprint.pprint(getattr(rcp, name), out)
out.write("\n")
out.write("def Parse(s):\n")
out.write("\treturn FakeParser()\n")
out.close()
def _WalkCallback(self, arg, directory, files):
# callback function for os.path.walk - no need to be member, but its
# close to the callers :)
callback, total_list = arg
for file in files:
fqn = os.path.join(directory, file).lower()
if file.endswith(".pyc") or file.endswith(".pyo"):
# See below - total_list == None means delete files,
# otherwise it is a list where the result is stored. Its a
# list simply due to the way os.walk works - only [0] is
# referenced
if total_list is None:
print "Deleting file", fqn
# Should do callback.PurgeProcess - left as an exercise :)
os.remove(fqn)
else:
total_list[0] += os.stat(fqn)[stat.ST_SIZE]
# and callback to the tool
if callback:
# for the sake of seeing the progress bar do its thing,
# we take longer than we need to...
# ACK - for some bizarre reason this screws up the XP
# cleanup manager - clues welcome!! :)
## print "Looking in", directory, ", but waiting a while..."
## time.sleep(3)
# now do it
used = total_list[0]
callback.ScanProgress(used, 0, "Looking at " + fqn)
def printHeader(self, file_path):
file_len = len(file_path)
from stat import ST_SIZE
file_size = os.stat(file_path)[ST_SIZE]
size_str = utils.formatSize(file_size)
size_len = len(size_str) + 5
if file_len + size_len >= self.terminal_width:
file_path = "..." + file_path[-(75 - size_len):]
file_len = len(file_path)
pat_len = self.terminal_width - file_len - size_len
printMsg("%s%s%s[ %s ]%s" %
(boldText(file_path, c=HEADER_COLOR()),
HEADER_COLOR(), " " * pat_len, size_str, Fore.RESET))
def _get_output_for(self, audio_file):
from stat import ST_SIZE
file_size = os.stat(audio_file.path)[ST_SIZE]
return formatSize(file_size)
def printHeader(self, filePath):
from stat import ST_SIZE
fileSize = os.stat(filePath)[ST_SIZE]
size_str = formatSize(fileSize)
print("\n%s\t%s[ %s ]%s" % (boldText(os.path.basename(filePath),
HEADER_COLOR()),
HEADER_COLOR(), size_str,
Fore.RESET))
print("-" * 79)
def checkSum():
"""
Return a long which can be used to know if any .py files have changed.
"""
val = 0
for root, dirs, files in os.walk(os.getcwd()):
for extension in EXTENSIONS:
for f in fnmatch.filter(files, extension):
stats = os.stat(os.path.join(root, f))
val += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return val
def importDF3(self, file, scale=1):
try:
f = open(file, 'rb');
size = os.stat(file)[stat.ST_SIZE]
except:
print("Could not open " + file + " for read");
return []
(x, y, z) = struct.unpack(self.__struct2byte3__, f.read(6) )
self.voxel = self.__create__(x, y, z)
self.maxX = x
self.maxY = y
self.maxZ = z
size = size-6
if (size == x*y*z): format = 8
elif (size == 2*x*y*z): format = 16
elif (size == 4*x*y*z): format = 32
if (format == 32):
for i in range(x*y*z):
self.voxel[i] = float(struct.unpack(self.__struct4byte__, f.read(4) )[0])
elif (format == 16):
for i in range(x*y*z):
self.voxel[i] = float(struct.unpack(self.__struct2byte__, f.read(2) )[0])
elif (format == 8):
for i in range(x*y*z):
self.voxel[i] = float(struct.unpack(self.__struct1byte__, f.read(1) )[0])
return self
#### Local classes not intended for user use
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
b_path = to_bytes(path, errors='surrogate_or_strict')
if os.path.exists(b_path):
(uid, gid) = self.user_and_group(path)
kwargs['uid'] = uid
kwargs['gid'] = gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
kwargs['owner'] = user
kwargs['group'] = group
st = os.lstat(b_path)
kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE])
# secontext not yet supported
if os.path.islink(b_path):
kwargs['state'] = 'link'
elif os.path.isdir(b_path):
kwargs['state'] = 'directory'
elif os.stat(b_path).st_nlink > 1:
kwargs['state'] = 'hard'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
kwargs['size'] = st[stat.ST_SIZE]
else:
kwargs['state'] = 'absent'
return kwargs
def test_seek(self):
if verbose:
print('create large file via seek (may be sparse file) ...')
with self.open(TESTFN, 'wb') as f:
f.write(b'z')
f.seek(0)
f.seek(size)
f.write(b'a')
f.flush()
if verbose:
print('check file size with os.fstat')
self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def test_osstat(self):
if verbose:
print('check file size with os.stat')
self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1)
def checkSum():
"""
Return a long which can be used to know if any .py files have changed.
"""
val = 0
for root, dirs, files in os.walk(os.getcwd()):
for extension in EXTENSIONS:
for f in fnmatch.filter(files, extension):
stats = os.stat(os.path.join(root, f))
val += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return val
def checkSum():
"""
Return a long which can be used to know if any .py files have changed.
"""
val = 0
for root, dirs, files in os.walk(os.getcwd()):
for extension in EXTENSIONS:
for f in fnmatch.filter(files, extension):
stats = os.stat(os.path.join(root, f))
val += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return val
def checkSum():
"""
Return a long which can be used to know if any .py files have changed.
"""
val = 0
for root, dirs, files in os.walk(os.getcwd()):
for extension in EXTENSIONS:
for f in fnmatch.filter(files, extension):
stats = os.stat(os.path.join(root, f))
val += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return val
def get_file_size(path):
return os.stat(path)[stat.ST_SIZE]
def test_seek(self):
if verbose:
print('create large file via seek (may be sparse file) ...')
with self.open(TESTFN, 'wb') as f:
f.write(b'z')
f.seek(0)
f.seek(size)
f.write(b'a')
f.flush()
if verbose:
print('check file size with os.fstat')
self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
def test_osstat(self):
if verbose:
print('check file size with os.stat')
self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1)
def getsize(p):
"""
Return the size of a file, reported by os.stat().
"""
st= os.stat(p)
return st[stat.ST_SIZE]