本文整理汇总了Python中os.chmod方法的典型用法代码示例。如果您正苦于以下问题:Python os.chmod方法的具体用法?Python os.chmod怎么用?Python os.chmod使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.chmod方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ensure_session_manager_plugin
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def ensure_session_manager_plugin():
session_manager_dir = os.path.join(config.user_config_dir, "bin")
PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
if shutil.which("session-manager-plugin", path=PATH):
subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
else:
os.makedirs(session_manager_dir, exist_ok=True)
target_path = os.path.join(session_manager_dir, "session-manager-plugin")
if platform.system() == "Darwin":
download_session_manager_plugin_macos(target_path=target_path)
elif platform.linux_distribution()[0] == "Ubuntu":
download_session_manager_plugin_linux(target_path=target_path)
else:
download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
return shutil.which("session-manager-plugin", path=PATH)
示例2: ensure_permissions
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [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
示例3: test_ensure_writable
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [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)
示例4: test_copymode_local_to_local_symlink_dont_follow
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [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)
示例5: test_copystat_local_to_local
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [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
示例6: test_copystat_local_to_local_symlink_dont_follow_fail
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def test_copystat_local_to_local_symlink_dont_follow_fail(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 = "follow_symlinks unavailable on this platform"
with pytest.raises(NotImplementedError, match=re.escape(expected)):
copystat(src_link, dst_link, follow_symlinks=False)
示例7: gunzip_file
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped.
"""
if tf.gfile.Exists(new_path):
tf.logging.info("File %s already exists, skipping unpacking" % new_path)
return
tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
# We may be unpacking into a newly created directory, add write mode.
mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
os.chmod(os.path.dirname(new_path), mode)
with gzip.open(gz_path, "rb") as gz_file:
with tf.gfile.GFile(new_path, mode="wb") as new_file:
for line in gz_file:
new_file.write(line)
示例8: test_found_win32
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def test_found_win32(self):
sys.platform = 'win32'
tempdir = os.environ['PATH'] = mkdtemp(self)
os.environ['PATHEXT'] = pathsep.join(('.com', '.exe', '.bat'))
f = join(tempdir, 'binary.exe')
with open(f, 'w'):
pass
os.chmod(f, 0o777)
self.assertEqual(which('binary'), f)
self.assertEqual(which('binary.exe'), f)
self.assertEqual(which(f), f)
self.assertIsNone(which('binary.com'))
os.environ['PATH'] = ''
self.assertEqual(which('binary', path=tempdir), f)
self.assertEqual(which('binary.exe', path=tempdir), f)
self.assertEqual(which(f, path=tempdir), f)
self.assertIsNone(which('binary.com', path=tempdir))
示例9: _run
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def _run(self, *args, **kwargs):
cmd = [self.binary, '-j', self.parallelism]
if mx.get_opts().very_verbose:
cmd += ['-v']
cmd += args
out = kwargs.get('out', mx.OutputCapture())
err = kwargs.get('err', subprocess.STDOUT)
if mx.get_opts().verbose:
if callable(out) and '-n' not in args:
out = mx.TeeOutputCapture(out)
if callable(err):
err = mx.TeeOutputCapture(err)
try:
rc = mx.run(cmd, nonZeroIsFatal=False, out=out, err=err, cwd=self.build_dir)
except OSError as e:
if e.errno != errno.EACCES:
mx.abort('Error executing \'{}\': {}'.format(' '.join(cmd), str(e)))
mx.logv('{} is not executable. Trying to change permissions...'.format(self.binary))
os.chmod(self.binary, 0o755)
self._run(*args, **kwargs) # retry
else:
not rc or mx.abort(rc if mx.get_opts().verbose else out.data) # pylint: disable=expression-not-assigned
示例10: set
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
filename = self._get_filename(key)
self._prune()
try:
fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
dir=self._path)
f = os.fdopen(fd, 'wb')
try:
pickle.dump(int(time() + timeout), f, 1)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
finally:
f.close()
rename(tmp, filename)
os.chmod(filename, self._mode)
except (IOError, OSError):
pass
示例11: copymode
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def copymode(src, dst, *, follow_symlinks=True):
"""Copy mode bits from src to dst.
If follow_symlinks is not set, symlinks aren't followed if and only
if both `src` and `dst` are symlinks. If `lchmod` isn't available
(e.g. Linux) this method does nothing.
"""
if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
if hasattr(os, 'lchmod'):
stat_func, chmod_func = os.lstat, os.lchmod
else:
return
elif hasattr(os, 'chmod'):
stat_func, chmod_func = os.stat, os.chmod
else:
return
st = stat_func(src)
chmod_func(dst, stat.S_IMODE(st.st_mode))
示例12: replace_gmsh
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def replace_gmsh():
fn_gmsh = path2bin('gmsh')
fn_gmsh_tmp = path2bin('gmsh_tmp')
# move
shutil.move(fn_gmsh, fn_gmsh_tmp)
# replace
if sys.platform == 'win32':
fn_script = fn_gmsh[:4] + '.cmd'
with open(fn_script, 'w') as f:
f.write('echo "GMSH"')
else:
with open(fn_gmsh, 'w') as f:
f.write('#! /bin/bash -e\n')
f.write(f'"echo" "$@"')
os.chmod(
fn_gmsh,
os.stat(fn_gmsh).st_mode |
stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)
yield
shutil.move(fn_gmsh_tmp, fn_gmsh)
示例13: ___test_folder_not_writeable
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def ___test_folder_not_writeable(self):
# make sure we get permissions error and not 'database is locked'
s = ts.SetupDbAndCredentials()
s.test_setup("test_folder_not_writeable", trash_files=True, trash_db=True)
try:
if os.name == "nt":
os.chmod(str(s.root), stat.S_IREAD)
else:
s.root.chmod(0o444)
with self.assertRaises(PermissionError):
s.gp.main([str(s.root), "--skip-shared-albums"])
finally:
if os.name == "nt":
os.chmod(str(s.root), stat.S_IWRITE | stat.S_IREAD)
else:
os.chmod(str(s.root), 0o777)
shutil.rmtree(str(s.root))
示例14: save
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def save(filename):
try:
os.mkdir('saves/')
except OSError:
pass
try:
data = unicornhathd.get_pixels()
data = repr(data)
data = data.replace('array', 'list')
print(filename, data)
file = open('saves/' + filename + '.py', 'w')
file.write("""#!/usr/bin/env python
import unicornhathd
import signal
unicornhathd.rotation(0)
pixels = {}
for x in range(unicornhathd.WIDTH):
for y in range(unicornhathd.HEIGHT):
r, g, b = pixels[x][y]
unicornhathd.set_pixel(x, y, r, g, b)
unicornhathd.show()
print("\\nShowing: {}\\nPress Ctrl+C to exit!")
signal.pause()
""".format(data, filename))
file.close()
os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC)
return("ok" + str(unicornhathd.get_pixels()))
except AttributeError:
print("Unable to save, please update")
print("unicornhathdhathd library!")
return("fail")
示例15: private_key_file
# 需要导入模块: import os [as 别名]
# 或者: from os import chmod [as 别名]
def private_key_file(self):
if not self.key_dir:
self.key_dir = '.'
if not self.private_key:
return None
key_name = '.' + md5(self.private_key.encode('utf-8')).hexdigest()
key_path = os.path.join(self.key_dir, key_name)
if not os.path.exists(key_path):
with open(key_path, 'w') as f:
f.write(self.private_key)
os.chmod(key_path, 0o400)
return key_path