Python stat.S_IREAD Examples

The following are 30 code examples of stat.S_IREAD(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module stat , or try the search function .
Example #1
Source File: config.py    From is-service-up with Apache License 2.0 6 votes vote down vote up
def ensure_private_ssh_key():
    global PRIVATE_SSH_KEY
    if PRIVATE_SSH_KEY:
        key_path = os.path.expanduser('~/.ssh')
        key_file = os.path.join(key_path, 'id_rsa')
        try:
            if not os.path.isdir(key_path):
                os.mkdir(key_path)
            if not os.path.isfile(key_file):
                shutil.copyfile(PRIVATE_SSH_KEY, key_file)
                os.chmod(key_file, stat.S_IWRITE | stat.S_IREAD)
        except (IOError, OSError) as error:
            PRIVATE_SSH_KEY = ''
            print(error)
        else:
            return True
    return False


# TODO: unify with frontend config 
Example #2
Source File: test_nt.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_access(self):
        f = file('new_file_name', 'w')
        f.close()
        
        self.assertEqual(nt.access('new_file_name', nt.F_OK), True)
        self.assertEqual(nt.access('new_file_name', nt.R_OK), True)
        self.assertEqual(nt.access('does_not_exist.py', nt.F_OK), False)
        self.assertEqual(nt.access('does_not_exist.py', nt.R_OK), False)

        nt.chmod('new_file_name', 0x100) # S_IREAD
        self.assertEqual(nt.access('new_file_name', nt.W_OK), False)
        nt.chmod('new_file_name', 0x80)  # S_IWRITE
            
        nt.unlink('new_file_name')
        
        nt.mkdir('new_dir_name')
        self.assertEqual(nt.access('new_dir_name', nt.R_OK), True)
        nt.rmdir('new_dir_name')
        
        self.assertRaises(TypeError, nt.access, None, 1) 
Example #3
Source File: test_nt.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_remove_negative(self):
        import stat
        self.assertRaisesNumber(WindowsError, errno.ENOENT, lambda : nt.remove('some_file_that_does_not_exist'))
        try:
            file('some_test_file.txt', 'w').close()
            nt.chmod('some_test_file.txt', stat.S_IREAD)
            self.assertRaisesNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
            nt.chmod('some_test_file.txt', stat.S_IWRITE)
            
            f = file('some_test_file.txt', 'w+')
            self.assertRaisesNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
            f.close()
        finally:
            nt.chmod('some_test_file.txt', stat.S_IWRITE)
            nt.unlink('some_test_file.txt')
            
            

    # rename tests 
Example #4
Source File: test_shutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_on_error(self):
        self.errorState = 0
        os.mkdir(TESTFN)
        self.childpath = os.path.join(TESTFN, 'a')
        f = open(self.childpath, 'w')
        f.close()
        old_dir_mode = os.stat(TESTFN).st_mode
        old_child_mode = os.stat(self.childpath).st_mode
        # Make unwritable.
        os.chmod(self.childpath, stat.S_IREAD)
        os.chmod(TESTFN, stat.S_IREAD)

        shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
        # Test whether onerror has actually been called.
        self.assertEqual(self.errorState, 2,
                            "Expected call to onerror function did not happen.")

        # Make writable again.
        os.chmod(TESTFN, old_dir_mode)
        os.chmod(self.childpath, old_child_mode)

        # Clean up.
        shutil.rmtree(TESTFN) 
Example #5
Source File: test_tmpdir.py    From pytest with MIT License 6 votes vote down vote up
def test_basetemp_with_read_only_files(testdir):
    """Integration test for #5524"""
    testdir.makepyfile(
        """
        import os
        import stat

        def test(tmp_path):
            fn = tmp_path / 'foo.txt'
            fn.write_text('hello')
            mode = os.stat(str(fn)).st_mode
            os.chmod(str(fn), mode & ~stat.S_IREAD)
    """
    )
    result = testdir.runpytest("--basetemp=tmp")
    assert result.ret == 0
    # running a second time and ensure we don't crash
    result = testdir.runpytest("--basetemp=tmp")
    assert result.ret == 0 
Example #6
Source File: _os.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """
    On Windows, some files are read-only (e.g. in in .svn dirs), so when
    rmtree() tries to remove them, an exception is thrown.
    We catch that here, remove the read-only attribute, and hopefully
    continue without problems.
    """
    exctype, value = exc_info[:2]
    # looking for a windows error
    if exctype is not WindowsError or 'Access is denied' not in str(value):
        raise
    # file type should currently be read only
    if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
        raise
    # convert to read/write
    os.chmod(path, stat.S_IWRITE)
    # use the original function to repeat the operation
    func(path) 
Example #7
Source File: injector.py    From pylane with GNU General Public License v3.0 6 votes vote down vote up
def ensure_code_file(self, code, file_path):
        """"""
        if file_path:
            file_path = os.path.abspath(file_path)
            if not os.path.isfile(file_path):
                raise RequirementsInvalid(
                    'Arg file_path is not a valid file.'
                )
            self.code_file = file_path
        else:
            if code:
                (fd, temp_file_path) = tempfile.mkstemp()
                with os.fdopen(fd, 'w') as f:
                    f.write(code)
                self.code_file = self.temp_file = temp_file_path
            else:
                raise RequirementsInvalid(
                    'Neither code nor code file_path specified.'
                )
        st = os.stat(self.code_file)
        os.chmod(self.code_file,
                 st.st_mode | stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) 
Example #8
Source File: test_shutil.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_on_error(self):
            self.errorState = 0
            os.mkdir(TESTFN)
            self.childpath = os.path.join(TESTFN, 'a')
            f = open(self.childpath, 'w')
            f.close()
            old_dir_mode = os.stat(TESTFN).st_mode
            old_child_mode = os.stat(self.childpath).st_mode
            # Make unwritable.
            os.chmod(self.childpath, stat.S_IREAD)
            os.chmod(TESTFN, stat.S_IREAD)

            shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
            # Test whether onerror has actually been called.
            self.assertEqual(self.errorState, 2,
                             "Expected call to onerror function did not happen.")

            # Make writable again.
            os.chmod(TESTFN, old_dir_mode)
            os.chmod(self.childpath, old_child_mode)

            # Clean up.
            shutil.rmtree(TESTFN) 
Example #9
Source File: util.py    From oss-ftp with MIT License 6 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    exctype, value = exc_info[:2]
    if not ((exctype is WindowsError and value.args[0] == 5) or #others
            (exctype is OSError and value.args[0] == 13) or #python2.4
            (exctype is PermissionError and value.args[3] == 5) #python3.3
            ):
        raise
    # file type should currently be read only
    if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
        raise
    # convert to read/write
    os.chmod(path, stat.S_IWRITE)
    # use the original function to repeat the operation
    func(path) 
Example #10
Source File: test_shutil.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_on_error(self):
        self.errorState = 0
        os.mkdir(TESTFN)
        self.childpath = os.path.join(TESTFN, 'a')
        f = open(self.childpath, 'w')
        f.close()
        old_dir_mode = os.stat(TESTFN).st_mode
        old_child_mode = os.stat(self.childpath).st_mode
        # Make unwritable.
        os.chmod(self.childpath, stat.S_IREAD)
        os.chmod(TESTFN, stat.S_IREAD)

        shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
        # Test whether onerror has actually been called.
        self.assertEqual(self.errorState, 2,
                            "Expected call to onerror function did not happen.")

        # Make writable again.
        os.chmod(TESTFN, old_dir_mode)
        os.chmod(self.childpath, old_child_mode)

        # Clean up.
        shutil.rmtree(TESTFN) 
Example #11
Source File: test_regression.py    From gphotos-sync with MIT License 6 votes vote down vote up
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)) 
Example #12
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: wallet.py    From torba with MIT License 6 votes vote down vote up
def write(self, json_dict):

        json_data = json.dumps(json_dict, indent=4, sort_keys=True)
        if self.path is None:
            return json_data

        temp_path = "%s.tmp.%s" % (self.path, os.getpid())
        with open(temp_path, "w") as f:
            f.write(json_data)
            f.flush()
            os.fsync(f.fileno())

        if os.path.exists(self.path):
            mode = os.stat(self.path).st_mode
        else:
            mode = stat.S_IREAD | stat.S_IWRITE
        try:
            os.rename(temp_path, self.path)
        except Exception:  # pylint: disable=broad-except
            os.remove(self.path)
            os.rename(temp_path, self.path)
        os.chmod(self.path, mode) 
Example #14
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
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 
Example #15
Source File: shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: test_buffered_mode.py    From signac with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_force_write_mode_with_permission_error(self):
        job = self.project.open_job(dict(a=0))
        job.init()
        job.doc.a = True
        x = job.doc.a
        path = os.path.dirname(job.doc._filename)
        mode = os.stat(path).st_mode
        logging.disable(logging.CRITICAL)
        try:
            assert job.doc.a == x
            with pytest.raises(BufferedFileError):
                with signac.buffered():
                    assert job.doc.a == x
                    job.doc.a = not x
                    assert job.doc.a == (not x)
                    os.chmod(path, S_IREAD)  # Trigger permissions error
        finally:
            logging.disable(logging.NOTSET)
            os.chmod(path, mode)
        assert job.doc.a == x 
Example #17
Source File: contract_test.py    From appstart with Apache License 2.0 5 votes vote down vote up
def test_make_hook_clauses(self):
        """Test the construction of hook clauses from a .conf.yaml file."""

        test_config = textwrap.dedent('''\
            name: Test1
            title: Test number 1
            lifecycle_point: POST_START''')
        self._add_file('validator_tests/test1.py.conf.yaml', test_config)

        # The default test file does not exist.
        with self.assertRaises(utils.AppstartAbort):
            contract.ContractValidator(self.module, config_file=self.conf_file)

        self._add_file(self.default_test_file, self.successful_hook)

        # The default test file is not executable
        with self.assertRaises(utils.AppstartAbort):
            contract.ContractValidator(self.module, config_file=self.conf_file)

        os.chmod(os.path.join(self.app_dir, self.default_test_file),
                 stat.S_IEXEC | stat.S_IREAD)

        # The 'description' attribute is missing from the configuration file.
        with self.assertRaises(utils.AppstartAbort):
            contract.ContractValidator(self.module, config_file=self.conf_file)

        test_config = textwrap.dedent('''\
            name: Test1
            title: Test number 1
            lifecycle_point: POST_START
            description: This is a test.''')
        self._add_file('validator_tests/test1.py.conf.yaml', test_config)

        # The initialization should be okay now.
        contract.ContractValidator(
            self.module,
            config_file=os.path.join(self.app_dir, 'app.yaml')) 
Example #18
Source File: misc.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example #19
Source File: misc.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example #20
Source File: misc.py    From pySINDy with MIT License 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example #21
Source File: test_cogapp.py    From cog with MIT License 5 votes vote down vote up
def setUp(self):
        super(WritabilityTests, self).setUp()
        makeFiles(self.d)
        self.testcog = os.path.join(self.tempdir, 'test.cog')
        os.chmod(self.testcog, stat.S_IREAD)   # Make the file readonly.
        assert not os.access(self.testcog, os.W_OK) 
Example #22
Source File: misc.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example #23
Source File: path.py    From pipenv with MIT License 5 votes vote down vote up
def is_readonly_path(fn):
    # type: (TPath) -> bool
    """Check if a provided path exists and is readonly.

    Permissions check is `bool(path.stat & stat.S_IREAD)` or `not
    os.access(path, os.W_OK)`
    """

    fn = fs_decode(fs_encode(fn))
    if os.path.exists(fn):
        file_stat = os.stat(fn).st_mode
        return not bool(file_stat & stat.S_IWRITE) or not os.access(fn, os.W_OK)
    return False 
Example #24
Source File: file_system_input_utils.py    From sagemaker-python-sdk with Apache License 2.0 5 votes vote down vote up
def _check_or_create_key_pair(sagemaker_session):
    if _check_key_pair_and_cleanup_old_artifacts(sagemaker_session):
        return
    ec2_client = sagemaker_session.boto_session.client("ec2")
    key_pair = ec2_client.create_key_pair(KeyName=KEY_NAME)
    with open(KEY_PATH, "w") as file:
        file.write(key_pair["KeyMaterial"])
    fd = os.open(KEY_PATH, os.O_RDONLY)
    os.fchmod(fd, stat.S_IREAD) 
Example #25
Source File: utils.py    From pipenv with MIT License 5 votes vote down vote up
def is_readonly_path(fn):
    """Check if a provided path exists and is readonly.

    Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)`
    """
    if os.path.exists(fn):
        return (os.stat(fn).st_mode & stat.S_IREAD) or not os.access(fn, os.W_OK)

    return False 
Example #26
Source File: session.py    From odoorpc with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save(name, data, rc_file='~/.odoorpcrc'):
    """Save the `data` session configuration under the name `name`
    in the `rc_file` file.

    >>> import odoorpc
    >>> odoorpc.session.save(
    ...     'foo',
    ...     {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',
    ...      'port': 8069, 'timeout': 120, 'database': 'db_name'
    ...      'user': 'admin', 'passwd': 'password'})    # doctest: +SKIP

    .. doctest::
        :hide:

        >>> import odoorpc
        >>> session = '%s_session' % DB
        >>> odoorpc.session.save(
        ...     session,
        ...     {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL,
        ...      'port': PORT, 'timeout': 120, 'database': DB,
        ...      'user': USER, 'passwd': PWD})
    """
    conf = ConfigParser()
    conf.read([os.path.expanduser(rc_file)])
    if not conf.has_section(name):
        conf.add_section(name)
    for key in data:
        value = data[key]
        conf.set(name, key, str(value))
    with open(os.path.expanduser(rc_file), 'w') as file_:
        os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE)
        conf.write(file_) 
Example #27
Source File: utils.py    From teleport with Apache License 2.0 5 votes vote down vote up
def tp_make_dir(path):
    """
    创建目录

    如果父目录不存在,则同时也创建之,目标是保证整个目录层次都存在,如果指定的目录已经存在,则视为成功(目的就是让这个目录存在)

    :param path: str
    :return: boolean
    """
    abs_path = os.path.abspath(path)

    if os.path.exists(abs_path):
        if os.path.isdir(abs_path):
            return True
        else:
            # log.e(u'An object named "%s" already exists. Can not create such directory.\n' % abs_path)
            return False

    base_name = os.path.basename(abs_path)
    parent_path = abs_path[:len(abs_path) - len(base_name)]
    if parent_path == path:
        return False

    if not os.path.exists(parent_path):
        # log.v('make_dir: %s\n' % parent_path)
        if not tp_make_dir(parent_path):
            return False
        os.mkdir(abs_path)
        # os.mkdir(abs_path, 0o777)
        os.chmod(abs_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
    else:
        if os.path.isdir(parent_path):
            os.mkdir(abs_path)
            # os.mkdir(abs_path, 0o777)
            os.chmod(abs_path, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
        else:
            # log.e(u'An object named "%s" already exists. Can not create such directory.\n' % parent_path)
            return False

    return True 
Example #28
Source File: misc.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def rmtree_errorhandler(func, path, exc_info):
    """On Windows, the files in .svn are read-only, so when rmtree() tries to
    remove them, an exception is thrown.  We catch that here, remove the
    read-only attribute, and hopefully continue without problems."""
    # if file type currently read only
    if os.stat(path).st_mode & stat.S_IREAD:
        # convert to read/write
        os.chmod(path, stat.S_IWRITE)
        # use the original function to repeat the operation
        func(path)
        return
    else:
        raise 
Example #29
Source File: wallet.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def write(self):
        s = json.dumps(self.data, indent=4, sort_keys=True)
        f = open(self.path,"w")
        f.write(s)
        f.close()
        if 'ANDROID_DATA' not in os.environ:
            import stat
            os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE) 
Example #30
Source File: simple_config.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def save_user_config(self):
        if not self.path: return

        path = os.path.join(self.path, "config")
        s = repr(self.user_config)
        f = open(path,"w")
        f.write( s )
        f.close()
        if self.get('gui') != 'android':
            import stat
            os.chmod(path, stat.S_IREAD | stat.S_IWRITE)