Skip to content

Commit

Permalink
Add a function to open a file with specific permission bits
Browse files Browse the repository at this point in the history
This uses the "opener" argument to open to pass extra arguments through
to os.open.
  • Loading branch information
dashea committed Jul 14, 2015
1 parent 2f16e79 commit 6c92744
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pyanaconda/iutil.py
Expand Up @@ -1343,3 +1343,19 @@ def open(*args, **kwargs): # pylint: disable=redefined-builtin
high-level languages handle this for you, like C's fopen.
"""
return eintr_retry_call(_open, *args, **kwargs)

def open_with_perm(path, mode='r', perm=0o777, **kwargs):
"""Open a file with the given permission bits.
This is more or less the same as using os.open(path, flags, perm), but
with the builtin open() semantics and return type instead of a file
descriptor.
:param str path: The path of the file to be opened
:param str mode: The same thing as the mode argument to open()
:param int perm: What permission bits to use if creating a new file
"""
def _opener(path, open_flags):
return eintr_retry_call(os.open, path, open_flags, perm)

return open(path, mode, opener=_opener, **kwargs)
20 changes: 20 additions & 0 deletions tests/pyanaconda_tests/iutil_test.py
Expand Up @@ -771,3 +771,23 @@ def parent_dir_test(self):

for d, r in dirs:
self.assertEquals(iutil.parent_dir(d), r)

def open_with_perm_test(self):
"""Test the open_with_perm function"""
# Create a directory for test files
test_dir = tempfile.mkdtemp()
try:
# Reset the umask
old_umask = os.umask(0)
try:
# Create a file with mode 0777
iutil.open_with_perm('test1', 'w', 0o777)
self.assertEqual(os.stat('test1').st_mode & 0o777, 0o777)

# Create a file with mode 0600
iutil.open_with_perm('test2', 'w', 0o600)
self.assertEqual(os.stat('test2').st_mode & 0o777, 0o600)
finally:
os.umask(old_umask)
finally:
shutil.rmtree(test_dir)

0 comments on commit 6c92744

Please sign in to comment.