Here are the examples of the python api os. taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
149 Examples
5
Example 1
Project: mythbox Source File: test_logfile.py
def test_defaultPermissions(self):
"""
Test the default permission of the log file: if the file exist, it
should keep the permission.
"""
f = file(self.path, "w")
os.chmod(self.path, 0707)
currentMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
f.close()
log1 = logfile.LogFile(self.name, self.dir)
self.assertEquals(stat.S_IMODE(os.stat(self.path)[stat.ST_MODE]),
currentMode)
5
Example 2
Project: SubliminalCollaborator Source File: test_logfile.py
def test_defaultPermissions(self):
"""
Test the default permission of the log file: if the file exist, it
should keep the permission.
"""
f = file(self.path, "w")
os.chmod(self.path, 0707)
currentMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
f.close()
log1 = logfile.LogFile(self.name, self.dir)
self.assertEqual(stat.S_IMODE(os.stat(self.path)[stat.ST_MODE]),
currentMode)
5
Example 3
Project: kupfer Source File: utils.py
def get_destfile_in_directory(directory, filename, extension=None):
"""Find a good destination for a file named @filename in path @directory.
Like get_destpath_in_directory, but returns an open file object, opened
atomically to avoid race conditions.
Return (fileobj, filepath)
"""
# retry if it fails
for retry in xrange(3):
destpath = get_destpath_in_directory(directory, filename, extension)
try:
fd = os.open(destpath, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)
except OSError, exc:
pretty.print_error(__name__, exc)
else:
return (os.fdopen(fd, "wb"), destpath)
return (None, None)
5
Example 4
Project: robothon Source File: test__datasource.py
def test_CachedHTTPFile(self):
localfile = valid_httpurl()
# Create a locally cached temp file with an URL based
# directory structure. This is similar to what Repository.open
# would do.
scheme, netloc, upath, pms, qry, frg = urlparse(localfile)
local_path = os.path.join(self.repos._destpath, netloc)
os.mkdir(local_path, 0700)
5
Example 5
def setUp(self):
super(TestReposCLI, self).setUp()
busybox_single_app_bundle_fixture(num_bundles=1)
single_specs_fixture()
self.temp_repos_dir = mkdtemp()
self.fake_override_dir = mkdtemp()
self.fake_from_dir = mkdtemp()
os.chmod(self.temp_repos_dir, 0777)
os.chmod(self.fake_override_dir, 0777)
os.chmod(self.fake_from_dir, 0777)
self.fake_override_repo_location = os.path.join(self.fake_override_dir, 'fake-repo')
self._set_up_fake_local_repo(path=self.fake_override_repo_location)
self.fake_from_repo_location = os.path.join(self.fake_from_dir, 'fake-repo')
self._set_up_fake_local_repo(path=self.fake_from_repo_location)
self.fake_source_repo_location = '/tmp/fake-repo'
self._set_up_fake_local_repo(path=self.fake_source_repo_location)
5
Example 6
def touch(self):
""" Set the access/modified times of this file to the current time.
Create the file if it does not exist.
"""
fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
os.close(fd)
os.utime(self, None)
5
Example 7
Project: redo Source File: state.py
def __init__(self, fid):
self.owned = False
self.fid = fid
self.lockfile = os.open(os.path.join(vars.BASE, '.redo/lock.%d' % fid),
os.O_RDWR | os.O_CREAT, 0666)
close_on_exec(self.lockfile, True)
assert(_locks.get(fid,0) == 0)
_locks[fid] = 1
5
Example 8
def setUp(self):
_test_c.COUNT = 0
try:
shutil.rmtree(_test_c.TEST_DIR)
except (OSError, IOError, ), e:
if e.errno != errno.ENOENT:
raise e
os.mkdir(_test_c.TEST_DIR, 00750)
os.mkdir(_test_c.ROOT1, 00750)
os.mkdir(_test_c.ROOT2, 00750)
_c.FSQ_ROOT = _test_c.ROOT1
normalize()
5
Example 9
Project: cloudpebble Source File: archive.py
@task(acks_late=True)
def export_user_projects(user_id):
user = User.objects.get(pk=user_id)
projects = Project.objects.filter(owner=user)
with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
filename = temp.name
with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as z:
for project in projects:
add_project_to_archive(z, project, prefix='cloudpebble-export/')
# Generate a URL
u = uuid.uuid4().hex
outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, 'cloudpebble-export')
os.makedirs(os.path.dirname(outfile), 0755)
shutil.copy(filename, outfile)
os.chmod(outfile, 0644)
5
Example 10
Project: pymo Source File: test_all.py
def get_new_environment_path() :
path=get_new_path("environment")
import os
try:
os.makedirs(path,mode=0700)
except os.error:
test_support.rmtree(path)
os.makedirs(path)
return path
5
Example 11
@staticmethod
def Lock():
lockfd = os.open(Config.BBS_ROOT + "bcache.lock", os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0600)
if (lockfd == None):
Log.warn("fail to create bcache.lock")
return None
BCache.SetReadOnly(False)
fcntl.flock(lockfd, fcntl.LOCK_EX)
return lockfd
5
Example 12
@classmethod
def Open(cls, filename):
"""Creates and opens a file to be used as a file-based lock.
@type filename: string
@param filename: path to the file to be locked
"""
# Using "os.open" is necessary to allow both opening existing file
# read/write and creating if not existing. Vanilla "open" will truncate an
# existing file -or- allow creating if not existing.
return cls(os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT, 0664), "w+"),
filename)
5
Example 13
Project: scalarizr Source File: openstack.py
def __init__(self):
platform.Platform.__init__(self)
if not linux.os.windows_family:
# Work over [Errno -3] Temporary failure in name resolution
# http://bugs.centos.org/view.php?id=4814
os.chmod('/etc/resolv.conf', 0755)
self._nova_conn_pool = LocalPool(_create_nova_connection)
self._swift_conn_pool = LocalPool(_create_swift_connection)
self._cinder_conn_pool = LocalPool(_create_cinder_connection)
5
Example 14
def tearDown(self):
"""
Restore back write rights on created paths: if tests modified the
rights, that will allow the paths to be removed easily afterwards.
"""
os.chmod(self.dir, 0777)
if os.path.exists(self.path):
os.chmod(self.path, 0777)
5
Example 15
Project: mrepo Source File: rpmSourceUtils.py
def saveHeader(hdr):
# print hdr
# print type(hdr)
cfg = config.initUp2dateConfig()
fileName = "%s/%s.%s.hdr" % (cfg["storageDir"],
string.join( (hdr['name'],
hdr['version'],
hdr['release']),
"-"),
hdr['arch'])
# print fileName
fd = os.open(fileName, os.O_WRONLY|os.O_CREAT, 0600)
os.write(fd, hdr.unload())
os.close(fd)
return 1
5
Example 16
def setUp(self):
super(IsolateOutdir, self).setUp()
# The tests assume the current directory is the file's directory.
os.mkdir(self.isolate_dir, 0700)
self.old_cwd = os.getcwd()
os.chdir(self.isolate_dir)
self.outdir = os.path.join(self.tempdir, 'isolated')
5
Example 17
Project: lever Source File: util.py
def read_file(path):
path = pathobj.os_stringify(path).encode('utf-8')
fd = os.open(path, os.O_RDONLY, 0777)
try:
data = ""
frame = os.read(fd, frame_size)
while frame != "":
data += frame
frame = os.read(fd, frame_size)
finally:
os.close(fd)
return data.decode('utf-8')
5
Example 18
Project: treadmill Source File: fs_test.py
@mock.patch('os.path.exists', mock.Mock(return_value=True))
@mock.patch('treadmill.syscall.unshare.unshare', mock.Mock(return_value=0))
@mock.patch('os.makedirs', mock.Mock(return_value=0))
def test_chroot_init_empty_existing(self):
"""Checks that chroot can be done over existing empty dir."""
fs.chroot_init('/var/bla')
os.makedirs.assert_called_with('/var/bla', mode=0777)
treadmill.syscall.unshare.unshare.assert_called_with(_CLONE_NEWNS)
5
Example 19
def setUp(self):
super(TestEnqueue, self).setUp()
for f,payload in ((_test_c.FILE, _test_c.PAYLOAD),
(_test_c.NON_ASCII_FILE,
_test_c.NON_ASCII_PAYLOAD)):
fd = os.open(f, os.O_WRONLY|os.O_CREAT, 00640)
try:
written = 0
payload = payload.encode('utf8')
while written < len(payload):
written += os.write(fd, payload[written:])
finally:
os.close(fd)
os.mkfifo(_test_c.FIFO, 00640)
5
Example 20
@dry_guard
def touch(self):
""" Set the access/modified times of this file to the current time.
Create the file if it does not exist.
"""
fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
os.close(fd)
os.utime(self, None)
5
Example 21
Project: mixminion Source File: Crypto.py
def pk_PEM_save(rsa, filename, password=None):
"""Save a PEM-encoded private key to a file. If <password> is provided,
encrypt the key using the password."""
fd = os.open(filename, os.O_WRONLY|os.O_CREAT,0600)
f = os.fdopen(fd, 'w')
if password:
rsa.PEM_write_key(f, 0, password)
else:
rsa.PEM_write_key(f, 0)
f.close()
5
Example 22
@unittest.skipUnless(hasattr(os, 'chmod'), 'os.chmod not available')
@unittest.skipUnless(hasattr(os, 'umask'), 'os.umask not available')
def test_dumbdbm_creation_mode(self):
try:
old_umask = os.umask(0002)
f = dumbdbm.open(_fname, 'c', 0637)
5
Example 23
def _store_pypirc(self, username, password):
"""Creates a default .pypirc file."""
rc = self._get_rc_file()
f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
try:
f.write(DEFAULT_PYPIRC % (username, password))
finally:
f.close()
5
Example 24
Project: dusty Source File: upgrade_test.py
@patch('dusty.commands.upgrade._get_binary_location')
def test_move_preserves_permissions(self, fake_get_binary_location):
os.chmod(self.file1_path, 0764)
os.chmod(self.file2_path, 0777)
previous_st_mode = os.stat(self.file1_path).st_mode
fake_get_binary_location.return_value = self.file1_path
_move_temp_binary_to_path(self.file2_path)
self.assertEqual(os.stat(self.file1_path).st_mode, previous_st_mode)
5
Example 25
def tearDown(self):
"""Remove directory with test data
"""
os.chmod(self.example_dir.path("unreadable.txt"),0644)
os.chmod(self.example_dir.path("group_unreadable.txt"),0644)
os.chmod(self.example_dir.path("group_unwritable.txt"),0644)
os.chmod(self.example_dir.path("program.exe"),0644)
self.example_dir.delete_directory()
5
Example 26
Project: google-apputils Source File: file_util_test.py
def testWriteGroup(self):
self.mox.StubOutWithMock(os, 'open')
self.mox.StubOutWithMock(os, 'write')
self.mox.StubOutWithMock(os, 'close')
self.mox.StubOutWithMock(os, 'chown')
gid = 'new gid'
os.open(self.file_path, os.O_WRONLY | os.O_TRUNC | os.O_CREAT,
0666).AndReturn(self.fd)
os.write(self.fd, self.sample_contents)
os.close(self.fd)
os.chown(self.file_path, -1, gid)
self.mox.ReplayAll()
file_util.Write(self.file_path, self.sample_contents, gid=gid)
self.mox.VerifyAll()
5
Example 27
Project: gmvault Source File: credential_utils.py
@classmethod
def store_passwd(cls, email, passwd):
"""
Encrypt and store gmail password
"""
passwd_file = '%s/%s.passwd' % (gmvault_utils.get_home_dir_path(), email)
fdesc = os.open(passwd_file, os.O_CREAT|os.O_WRONLY, 0600)
cipher = blowfish.Blowfish(cls.get_secret_key(cls.SECRET_FILEPATH % (gmvault_utils.get_home_dir_path())))
cipher.initCTR()
encrypted = cipher.encryptCTR(passwd)
the_bytes = os.write(fdesc, encrypted)
os.close(fdesc)
if the_bytes < len(encrypted):
raise Exception("Error: Cannot write password in %s" % (passwd_file))
5
Example 28
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
# Note that the stock python on SunOS has a bug
# where fcntl.flock(fd, LOCK_EX) always fails
# with EBADF, that's why we use this F_SETLK
# hack instead.
fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
if sys.platform.startswith('aix'):
# Python on AIX is compiled with LARGEFILE support, which changes the
# struct size.
op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
else:
op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
fcntl.fcntl(fd, fcntl.F_SETLK, op)
return subprocess.call(cmd_list)
5
Example 29
@staticmethod
def Lock():
#try:
#SemLock.Lock(Config.UCACHE_SEMLOCK, timeout = 10);
#return 0;
#except BusyError:
#return -1;
# Log.debug("Utmp.Lock enter()")
lockf = os.open(Config.BBS_ROOT + "UTMP", os.O_RDWR | os.O_CREAT, 0600)
if (lockf < 0):
Log.error("Fail to open lock file!")
raise Exception("fail to lock!")
Util.FLock(lockf, shared = False)
# Log.debug("Utmp.Lock succ()")
return lockf
5
Example 30
Project: pyrocore Source File: path.py
def touch(self):
""" Set the access/modified times of this file to the current time.
Create the file if it does not exist.
"""
def do_touch():
fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
os.close(fd)
os.utime(self, None)
dry("touch %s" % (self), do_touch)
5
Example 31
Project: rsync-time-machine Source File: time-machine.py
def flock_exclusive():
''' lock so only one snapshot of current config is running '''
fd = os.open(cfg['lock_file'], os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0600)
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
return False
return fd
5
Example 32
Project: sugar-toolkit-gtk3 Source File: activityfactory.py
def open_log_file(activity):
i = 1
while True:
path = env.get_logs_path('%s-%s.log' % (activity.get_bundle_id(), i))
try:
fd = os.open(path, os.O_EXCL | os.O_CREAT | os.O_WRONLY, 0644)
f = os.fdopen(fd, 'w', 0)
return (path, f)
except OSError, e:
if e.errno == EEXIST:
i += 1
elif e.errno == ENOSPC:
# not the end of the world; let's try to keep going.
return ('/dev/null', open('/dev/null', 'w'))
else:
raise e
5
Example 33
Project: mythbox Source File: test_logfile.py
def testModePreservation(self):
"""
Check rotated files have same permissions as original.
"""
f = open(self.path, "w").close()
os.chmod(self.path, 0707)
mode = os.stat(self.path)[stat.ST_MODE]
log = logfile.LogFile(self.name, self.dir)
log.write("abc")
log.rotate()
self.assertEquals(mode, os.stat(self.path)[stat.ST_MODE])
5
Example 34
Project: treadmill Source File: fs_test.py
@mock.patch('os.path.isdir', mock.Mock(return_value=False))
@mock.patch('treadmill.syscall.unshare.unshare', mock.Mock(return_value=0))
@mock.patch('os.makedirs', mock.Mock(return_value=0))
def test_chroot_init_ok(self):
"""Mock test, verifies root directory created and unshare called."""
fs.chroot_init('/var/bla')
os.makedirs.assert_called_with('/var/bla', mode=0777)
treadmill.syscall.unshare.unshare.assert_called_with(_CLONE_NEWNS)
5
Example 35
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
# Note that the stock python on SunOS has a bug
# where fcntl.flock(fd, LOCK_EX) always fails
# with EBADF, that's why we use this F_SETLK
# hack instead.
fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
fcntl.fcntl(fd, fcntl.F_SETLK, op)
return subprocess.call(cmd_list)
5
Example 36
def unzip (filename, targetdir):
"""Unzip given zipfile into targetdir."""
if isinstance(targetdir, unicode):
targetdir = str(targetdir)
zf = zipfile.ZipFile(filename)
for name in zf.namelist():
if name.endswith('/'):
os.mkdir(os.path.join(targetdir, name), 0700)
else:
outfile = open(os.path.join(targetdir, name), 'wb')
try:
outfile.write(zf.read(name))
finally:
outfile.close()
5
Example 37
def _try_lock(self):
try:
fd = os.open(self.path, os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0666)
except OSError:
return
try:
os.write(fd, '%s\n' % os.getpid())
finally:
os.close(fd)
5
Example 38
Project: archivematica Source File: executeOrRunSubProcess.py
def createAndRunScript(text, stdIn="", printing=True, arguments=[], env_updates={}):
# Output the text to a /tmp/ file
scriptPath = "/tmp/" + uuid.uuid4().__str__()
FILE = os.open(scriptPath, os.O_WRONLY | os.O_CREAT, 0770)
os.write(FILE, text)
os.close(FILE)
cmd = [scriptPath]
cmd.extend(arguments)
# Run it
ret = launchSubProcess(cmd, stdIn="", printing=True, env_updates=env_updates)
# Remove the temp file
os.remove(scriptPath)
return ret
5
Example 39
def setUp(self):
"""Build directory with test data
"""
self.example_dir = ExampleDirLinks()
self.wd = self.example_dir.create_directory()
self.example_dir.add_file("unreadable.txt")
self.example_dir.add_file("group_unreadable.txt")
self.example_dir.add_file("group_unwritable.txt")
self.example_dir.add_file("program.exe")
os.chmod(self.example_dir.path("spider.txt"),0664)
os.chmod(self.example_dir.path("web"),0775)
os.chmod(self.example_dir.path("unreadable.txt"),0044)
os.chmod(self.example_dir.path("group_unreadable.txt"),0624)
os.chmod(self.example_dir.path("group_unwritable.txt"),0644)
os.chmod(self.example_dir.path("program.exe"),0755)
self.example_dir.add_link("program","program.exe")
5
Example 40
def touch(fileName):
""" Set the access/modified times of this file to the current time. Create the file if
it does not exist """
fd = os.open(fileName, os.O_WRONLY | os.O_CREAT, 0666)
os.close(fd)
os.utime(fileName, None)
5
Example 41
Project: cauliflowervest Source File: util.py
def SafeOpen(path, mode, open_=open):
"""Opens a file, guaranteeing that its directory exists, and makes it 0600.
Args:
path: str, path to the file to open, just like open().
mode: str, open mode to perform, just like open().
open_: callable, dependency injection for tests only.
Returns:
A handle to the open file, just like open().
"""
try:
os.makedirs(os.path.dirname(path), 0700)
os.mknod(path, 0600 | stat.S_IFREG)
except OSError:
# File exists.
pass
return open_(path, mode)
3
Example 42
Project: autotest Source File: build_externals.py
def main():
"""
Find all ExternalPackage classes defined in this file and ask them to
fetch, build and install themselves.
"""
logging_manager.configure_logging(BuildExternalsLoggingConfig(),
verbose=True)
os.umask(022)
3
Example 43
Project: avocado-vt Source File: utils_disk.py
@error_context.context_aware
def close(self):
error_context.context(
"Creating unattended install CD image %s" % self.path)
g_cmd = ('mkisofs -o %s -max-iso9660-filenames '
'-relaxed-filenames -D --input-charset iso8859-1 '
'%s' % (self.path, self.mount))
process.run(g_cmd, verbose=DEBUG)
os.chmod(self.path, 0755)
cleanup(self.mount)
logging.debug("unattended install CD image %s successfully created",
self.path)
3
Example 44
@error.context_aware
def close(self):
error.context("Creating unattended install CD image %s" % self.path)
g_cmd = ('mkisofs -o %s -max-iso9660-filenames '
'-relaxed-filenames -D --input-charset iso8859-1 '
'%s' % (self.path, self.mount))
utils.run(g_cmd, verbose=DEBUG)
os.chmod(self.path, 0755)
cleanup(self.mount)
logging.debug("unattended install CD image %s successfully created",
self.path)
3
Example 45
Project: Observatory Source File: Repository.py
def clone_svn_repo(clone_url, destination_dir, fresh_clone = False):
if fresh_clone:
# make the repo's directory
try:
os.makedirs(destination_dir, 0770)
except OSError as e:
pass
clone_cmdline = ["git", "svn", "clone", clone_url, destination_dir]
else:
clone_cmdline = ["git", "svn", "fetch"]
if subprocess.call(clone_cmdline, cwd = destination_dir) != 0:
raise Repository.CheckoutFailureException(" ".join(clone_cmdline))
3
Example 46
Project: bleachbit Source File: FileUtilities.py
def wipe_contents(path, truncate=True):
"""Wipe files contents
http://en.wikipedia.org/wiki/Data_remanence
2006 NIST Special Publication 800-88 (p. 7): "Studies have
shown that most of today's media can be effectively cleared
by one overwrite"
"""
size = getsize(path)
try:
f = open(path, 'wb')
except IOError, e:
if e.errno == errno.EACCES: # permission denied
os.chmod(path, 0200) # user write only
f = open(path, 'wb')
3
Example 47
Project: livecd-tools Source File: kickstart.py
def write_wepkey(self, network):
if not network.wepkey:
return
p = self.path("/etc/sysconfig/network-scripts/keys-" + network.device)
f = file(p, "w+")
os.chmod(p, 0600)
3
Example 48
Project: pulp Source File: test_launcher.py
@mock.patch('os.path.expanduser')
@mock.patch('sys.stderr')
def test_exists_with_wrong_perms(self, mock_stderr, mock_expanduser):
mock_expanduser.return_value = self.pulppath
os.mkdir(self.pulppath, 0755)
launcher.ensure_user_pulp_dir()
self.assertEqual(mock_stderr.write.call_count, 1)
message = mock_stderr.write.call_args[0][0]
# make sure it prints a warning to stderr
self.assertTrue(message.startswith('Warning:'))
3
Example 49
def test_dumbdbm_creation_mode(self):
# On platforms without chmod, don't do anything.
if not (hasattr(os, 'chmod') and hasattr(os, 'umask')):
return
try:
old_umask = os.umask(0002)
f = dumbdbm.open(_fname, 'c', 0637)
3
Example 50
def write_hosts(self, hostname):
localline = ""
if hostname and hostname != "localhost.localdomain":
localline += hostname + " "
l = hostname.split(".")
if len(l) > 1:
localline += l[0] + " "
localline += "localhost.localdomain localhost"
path = self.path("/etc/hosts")
f = file(path, "w+")
os.chmod(path, 0644)