本文整理汇总了Python中os.stat方法的典型用法代码示例。如果您正苦于以下问题:Python os.stat方法的具体用法?Python os.stat怎么用?Python os.stat使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.stat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_server
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def setup_server():
def break_header():
# Add a header after finalize that is invalid
cherrypy.serving.response.header_list.append((2, 3))
cherrypy.tools.break_header = cherrypy.Tool(
'on_end_resource', break_header)
class Root:
@cherrypy.expose
def index(self):
return 'hello'
@cherrypy.config(**{'tools.break_header.on': True})
def start_response_error(self):
return 'salud!'
@cherrypy.expose
def stat(self, path):
with cherrypy.HTTPError.handle(OSError, 404):
os.stat(path)
root = Root()
cherrypy.tree.mount(root)
示例2: get_device_type
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def get_device_type(filename):
"""
Get the device type of a device file.
``filename`` is a string containing the path of a device file.
Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
``filename`` is a block device. Raise :exc:`~exceptions.ValueError` if
``filename`` is no device file at all. Raise
:exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
its metadata was inaccessible.
.. versionadded:: 0.15
"""
mode = os.stat(filename).st_mode
if stat.S_ISCHR(mode):
return 'char'
elif stat.S_ISBLK(mode):
return 'block'
else:
raise ValueError('not a device file: {0!r}'.format(filename))
示例3: is_block
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def is_block(usb_disk):
"""
Function to detect if the USB is block device
:param usb_disk: USB disk path
:return: True is devie is block device else False
"""
import stat
if platform.system() == 'Linux':
if len(usb_disk) != 9:
return False
elif platform.system() == 'Windows':
if len(usb_disk) != 2:
return False
else:
return True
try:
mode = os.stat(usb_disk).st_mode
gen.log(mode)
gen.log(stat.S_ISBLK(mode))
except:
return False
return stat.S_ISBLK(mode)
示例4: _download_and_uncompress_dataset
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def _download_and_uncompress_dataset(dataset_dir):
"""Downloads cifar10 and uncompresses it locally.
Args:
dataset_dir: The directory where the temporary files are stored.
"""
filename = _DATA_URL.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
示例5: download_and_uncompress_tarball
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def download_and_uncompress_tarball(tarball_url, dataset_dir):
"""Downloads the `tarball_url` and uncompresses it locally.
Args:
tarball_url: The URL of a tarball file.
dataset_dir: The directory where the temporary files are stored.
"""
filename = tarball_url.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(tarball_url, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
示例6: maybe_download_and_extract
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def maybe_download_and_extract():
"""Download and extract the tarball from Alex's website."""
dest_directory = FLAGS.data_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
extracted_dir_path = os.path.join(dest_directory, 'cifar-10-batches-bin')
if not os.path.exists(extracted_dir_path):
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
示例7: GetFileChecksum
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def GetFileChecksum(self, filepath):
"""Generates checksum of given file.
Args:
filepath: String of filepath.
Returns:
f_hash: SHA1 hash for the file provided in filepath.
"""
statinfo = os.stat(filepath)
if statinfo.st_size/1048576 < 200:
f_content = open(filepath, 'r').read()
f_hash = hashlib.sha1(f_content).hexdigest()
return f_hash
else:
cmd = ['shasum', filepath]
(stdout, unused_sterr, unused_rc) = RunProcess(cmd)
return stdout.split()[0]
示例8: ensure_permissions
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def ensure_permissions(mode_flags=stat.S_IWUSR):
"""decorator to ensure a filename has given permissions.
If changed, original permissions are restored after the decorated
modification.
"""
def decorator(f):
def modify(filename, *args, **kwargs):
m = chmod_perms(filename) if exists(filename) else mode_flags
if not m & mode_flags:
os.chmod(filename, m | mode_flags)
try:
return f(filename, *args, **kwargs)
finally:
# restore original permissions
if not m & mode_flags:
os.chmod(filename, m)
return modify
return decorator
# Open filename, checking for read permission
示例9: test_ensure_writable
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_ensure_writable():
# Test ensure writable decorator
with InTemporaryDirectory():
with open('test.bin', 'wt') as fobj:
fobj.write('A line\n')
# Set to user rw, else r
os.chmod('test.bin', 0o644)
st = os.stat('test.bin')
@ensure_writable
def foo(fname):
pass
foo('test.bin')
assert_equal(os.stat('test.bin'), st)
# No-one can write
os.chmod('test.bin', 0o444)
st = os.stat('test.bin')
foo('test.bin')
assert_equal(os.stat('test.bin'), st)
示例10: copymode
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def copymode(src, dst, follow_symlinks=True, **kwargs):
"""
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the
limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's
attribute is set to.
If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode
of dst itself (rather than the file it points to).
This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the
current working directory.
:param src: The src file or directory to copy the read only flag from.
:param dst: The dst file or directory to copy the read only flag to.
:param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
:param kwargs: Common arguments used to build the SMB Session for any UNC paths.
"""
src_mode = stat.S_IMODE(_get_file_stat(src, follow_symlinks, **kwargs).st_mode)
norm_dst = ntpath.normpath(dst)
if norm_dst.startswith('\\\\'):
read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
_set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs)
else:
_local_chmod(dst, src_mode, follow_symlinks)
示例11: test_copymode_remote_to_local
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_copymode_remote_to_local(smb_share, tmpdir):
test_dir = tmpdir.mkdir("test")
src_filename = "%s\\source.txt" % smb_share
dst_filename = "%s\\target.txt" % test_dir
with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
fd.write(u"content")
with open(dst_filename, mode='w') as fd:
fd.write(u"content")
copymode(src_filename, dst_filename)
actual = os.stat(dst_filename).st_mode
assert stat.S_IMODE(actual) & stat.S_IWRITE == 0
remove(src_filename)
with open_file(src_filename, mode='w') as fd:
fd.write(u"content")
copymode(src_filename, dst_filename)
actual = os.stat(dst_filename).st_mode
assert stat.S_IMODE(actual) & stat.S_IWRITE == stat.S_IWRITE
示例12: test_copymode_local_to_local_symlink_dont_follow
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_copymode_local_to_local_symlink_dont_follow(tmpdir):
test_dir = tmpdir.mkdir('test')
src_filename = "%s\\source.txt" % test_dir
dst_filename = "%s\\target.txt" % test_dir
with open(src_filename, mode='w') as fd:
fd.write(u"content")
os.chmod(src_filename, stat.S_IREAD)
with open(dst_filename, mode='w') as fd:
fd.write(u"content")
src_link = "%s\\source-link.txt" % test_dir
dst_link = "%s\\target-link.txt" % test_dir
os.symlink(src_filename, src_link)
os.symlink(dst_filename, dst_link)
expected = "chmod: follow_symlinks unavailable on this platform"
with pytest.raises(NotImplementedError, match=re.escape(expected)):
copymode(src_link, dst_link, follow_symlinks=False)
示例13: test_copystat_local_to_remote
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_copystat_local_to_remote(smb_share, tmpdir):
test_dir = tmpdir.mkdir("test")
src_filename = "%s\\source.txt" % test_dir
dst_filename = "%s\\target.txt" % smb_share
with open(src_filename, mode='w') as fd:
fd.write(u"content")
os.chmod(src_filename, stat.S_IREAD)
os.utime(src_filename, (1024, 1024))
with open_file(dst_filename, mode='w') as fd:
fd.write(u"content")
copystat(src_filename, dst_filename)
actual = smbclient_stat(dst_filename)
assert actual.st_atime == 1024
assert actual.st_mtime == 1024
assert actual.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == FileAttributes.FILE_ATTRIBUTE_READONLY
示例14: test_copystat_remote_to_local
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_copystat_remote_to_local(smb_share, tmpdir):
test_dir = tmpdir.mkdir("test")
src_filename = "%s\\source.txt" % smb_share
dst_filename = "%s\\target.txt" % test_dir
with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
fd.write(u"content")
utime(src_filename, times=(1024, 1024))
with open(dst_filename, mode='w') as fd:
fd.write(u"content")
copystat(src_filename, dst_filename)
actual = os.stat(dst_filename)
assert actual.st_atime == 1024
assert actual.st_mtime == 1024
assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0
示例15: test_copystat_local_to_local
# 需要导入模块: import os [as 别名]
# 或者: from os import stat [as 别名]
def test_copystat_local_to_local(tmpdir):
test_dir = tmpdir.mkdir("test")
src_filename = "%s\\source.txt" % test_dir
dst_filename = "%s\\target.txt" % test_dir
with open(src_filename, mode='w') as fd:
fd.write(u"content")
os.chmod(src_filename, stat.S_IREAD)
os.utime(src_filename, (1024, 1024))
with open(dst_filename, mode='w') as fd:
fd.write(u"content")
copystat(src_filename, dst_filename)
actual = os.stat(dst_filename)
assert actual.st_atime == 1024
assert actual.st_mtime == 1024
assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0