Python os.O_RDONLY Examples

The following are 30 code examples of os.O_RDONLY(). 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 os , or try the search function .
Example #1
Source File: terminalsize.py    From asciidots with GNU Affero General Public License v3.0 7 votes vote down vote up
def _get_terminal_size_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            cr = struct.unpack('hh',
                               fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
            return cr
        except:
            pass
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (os.environ['LINES'], os.environ['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0]) 
Example #2
Source File: TerminalSize.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def _get_terminal_size_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            cr = struct.unpack('hh',
                               fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
            return cr
        except:
            pass
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (os.environ['LINES'], os.environ['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0]) 
Example #3
Source File: capture.py    From py with MIT License 6 votes vote down vote up
def start(self):
        try:
            os.fstat(self._savefd)
        except OSError:
            raise ValueError("saved filedescriptor not valid, "
                "did you call start() twice?")
        if self.targetfd == 0 and not self.tmpfile:
            fd = os.open(devnullpath, os.O_RDONLY)
            os.dup2(fd, 0)
            os.close(fd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], DontReadFromInput())
        else:
            os.dup2(self.tmpfile.fileno(), self.targetfd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], self.tmpfile) 
Example #4
Source File: programs.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def start(self) -> None:
        self.current_frame = [0 for _ in range(self.bars)]
        self.growing_frame = b""
        try:
            # delete old contents of the pipe
            os.remove(self.cava_fifo_path)
        except FileNotFoundError:
            # the file does not exist
            pass
        try:
            os.mkfifo(self.cava_fifo_path)
        except FileExistsError:
            # the file already exists
            logging.info("%s already exists while starting", self.cava_fifo_path)

        self.cava_process = subprocess.Popen(
            ["cava", "-p", os.path.join(settings.BASE_DIR, "config/cava.config")],
            cwd=settings.BASE_DIR,
        )
        # cava_fifo = open(cava_fifo_path, 'r')
        self.cava_fifo = os.open(self.cava_fifo_path, os.O_RDONLY | os.O_NONBLOCK) 
Example #5
Source File: test_regrtest.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_huntrleaks_fd_leak(self):
        # test --huntrleaks for file descriptor leak
        code = textwrap.dedent("""
            import os
            import unittest
            from test import support

            class FDLeakTest(unittest.TestCase):
                def test_leak(self):
                    fd = os.open(__file__, os.O_RDONLY)
                    # bug: never close the file descriptor

            def test_main():
                support.run_unittest(FDLeakTest)
        """)
        self.check_leak(code, 'file descriptors') 
Example #6
Source File: capture.py    From python-netsurv with MIT License 6 votes vote down vote up
def start(self):
        try:
            os.fstat(self._savefd)
        except OSError:
            raise ValueError("saved filedescriptor not valid, "
                "did you call start() twice?")
        if self.targetfd == 0 and not self.tmpfile:
            fd = os.open(devnullpath, os.O_RDONLY)
            os.dup2(fd, 0)
            os.close(fd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], DontReadFromInput())
        else:
            os.dup2(self.tmpfile.fileno(), self.targetfd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], self.tmpfile) 
Example #7
Source File: test_fcntl.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_fcntl_64_bit(self):
        # Issue #1309352: fcntl shouldn't fail when the third arg fits in a
        # C 'long' but not in a C 'int'.
        try:
            cmd = fcntl.F_NOTIFY
            # This flag is larger than 2**31 in 64-bit builds
            flags = fcntl.DN_MULTISHOT
        except AttributeError:
            self.skipTest("F_NOTIFY or DN_MULTISHOT unavailable")
        fd = os.open(os.path.dirname(os.path.abspath(TESTFN)), os.O_RDONLY)
        try:
            # This will raise OverflowError if issue1309352 is present.
            fcntl.fcntl(fd, cmd, flags)
        except IOError:
            pass  # Running on a system that doesn't support these flags.
        finally:
            os.close(fd) 
Example #8
Source File: forking.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def main():
        '''
        Run code specified by data received over pipe
        '''
        assert is_forking(sys.argv)

        handle = int(sys.argv[-1])
        fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
        from_parent = os.fdopen(fd, 'rb')

        process.current_process()._inheriting = True
        preparation_data = load(from_parent)
        prepare(preparation_data)
        self = load(from_parent)
        process.current_process()._inheriting = False

        from_parent.close()

        exitcode = self._bootstrap()
        exit(exitcode) 
Example #9
Source File: test_fd.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_write(self):
        test_filename = "tmp.write.test"
        
        # trivial write
        fd = os.open(test_filename, flags)
        self.assertEqual(os.write(fd, "42"), 2)
        os.close(fd)
        os.unlink(test_filename)

        # write to closed file
        fd = os.open(test_filename, flags)
        os.close(fd)
        self.assertRaisesMessage(OSError, "[Errno 9] Bad file descriptor", os.write, fd, "42")
        os.unlink(test_filename)
        
        # write to file with wrong permissions
        fd = os.open(test_filename, os.O_CREAT | os.O_TRUNC | os.O_RDONLY)
        self.assertRaisesMessage(OSError, "[Errno -2146232800] Can not write to " + test_filename,  os.write, fd, "42")
        os.close(fd)
        os.unlink(test_filename) 
Example #10
Source File: parallel.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def redirect_io(log_file='/dev/null'):
    # Always redirect stdin.
    in_fd = os.open('/dev/null', os.O_RDONLY)
    try:
        os.dup2(in_fd, 0)
    finally:
        os.close(in_fd)

    out_fd = os.open(log_file, os.O_WRONLY | os.O_CREAT)
    try:
        os.dup2(out_fd, 2)
        os.dup2(out_fd, 1)
    finally:
        os.close(out_fd)

    sys.stdin = os.fdopen(0, 'r')
    sys.stdout = os.fdopen(1, 'w')
    sys.stderr = os.fdopen(2, 'w') 
Example #11
Source File: test_local.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test_get_secret(self):
        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        secret_id = uuidutils.generate_uuid()
        # Attempt to retrieve the secret
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock):
            local_cert_mgr.LocalCertManager.get_secret(None, secret_id)

        # Verify the correct files were opened
        flags = os.O_RDONLY
        open_mock.assert_called_once_with('/tmp/{0}.crt'.format(secret_id),
                                          flags)

        # Test failure path
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock) as mock_open:
            mock_open.side_effect = IOError
            self.assertRaises(exceptions.CertificateRetrievalException,
                              local_cert_mgr.LocalCertManager.get_secret,
                              None, secret_id) 
Example #12
Source File: common.py    From deplicate with MIT License 6 votes vote down vote up
def _readflags(sequential, direct):
    flags = os.O_RDONLY
    try:
        flags |= os.O_BINARY
        if sequential is not None:
            flags |= os.O_SEQUENTIAL if sequential else os.O_RANDOM

    except AttributeError:
        pass

    try:
        if direct:
            flags |= os.O_DIRECT
            read = directio.read
        else:
            raise AttributeError

    except AttributeError:
        read = os.read

    return read, flags 
Example #13
Source File: consle_width.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0]) 
Example #14
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_terminal_size():
    """Returns a tuple (x, y) representing the width(x) and the height(x)
    in characters of the terminal window."""
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            import struct
            cr = struct.unpack(
                'hh',
                fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')
            )
        except:
            return None
        if cr == (0, 0):
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
    return int(cr[1]), int(cr[0]) 
Example #15
Source File: tarfile.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __init__(self, name, mode):
        mode = {
            "r": os.O_RDONLY,
            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
        }[mode]
        if hasattr(os, "O_BINARY"):
            mode |= os.O_BINARY
        self.fd = os.open(name, mode, 0o666) 
Example #16
Source File: tempfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _stat(fn):
        fd = _os.open(fn, _os.O_RDONLY)
        _os.close(fd) 
Example #17
Source File: test_local.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _get_cert(self, cert_id):
        fd_mock = mock.mock_open()
        fd_mock.side_effect = [
            mock.mock_open(read_data=self.certificate).return_value,
            mock.mock_open(read_data=self.private_key).return_value,
            mock.mock_open(read_data=self.intermediates).return_value,
            mock.mock_open(read_data=self.private_key_passphrase).return_value
        ]
        open_mock = mock.Mock()
        # Attempt to retrieve the cert
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock):
            data = local_cert_mgr.LocalCertManager.get_cert(None, cert_id)

        # Verify the correct files were opened
        flags = os.O_RDONLY
        open_mock.assert_has_calls([
            mock.call(os.path.join('/tmp/{0}.crt'.format(cert_id)), flags),
            mock.call(os.path.join('/tmp/{0}.key'.format(cert_id)), flags),
            mock.call(os.path.join('/tmp/{0}.int'.format(cert_id)), flags),
            mock.call(os.path.join('/tmp/{0}.pass'.format(cert_id)), flags)
        ], any_order=True)

        # The returned data should be a Cert object
        self.assertIsInstance(data, cert.Cert)

        return data 
Example #18
Source File: local.py    From octavia with Apache License 2.0 5 votes vote down vote up
def get_secret(context, secret_ref):
        """Retrieves a secret payload by reference.

        :param context: Ignored in this implementation
        :param secret_ref: The secret reference ID

        :return: The secret payload
        :raises CertificateStorageException: if secret retrieval fails
        """
        LOG.info("Loading secret %s from the local filesystem.", secret_ref)

        filename_base = os.path.join(CONF.certificates.storage_path,
                                     secret_ref)

        filename_secret = "{0}.crt".format(filename_base)

        secret_data = None

        flags = os.O_RDONLY
        try:
            with os.fdopen(os.open(filename_secret, flags)) as secret_file:
                secret_data = secret_file.read()
        except IOError:
            LOG.error("Failed to read secret for %s.", secret_ref)
            raise exceptions.CertificateRetrievalException(ref=secret_ref)

        return secret_data 
Example #19
Source File: _pslinux.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def file_flags_to_mode(flags):
    """Convert file's open() flags into a readable string.
    Used by Process.open_files().
    """
    modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
    mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
    if flags & os.O_APPEND:
        mode = mode.replace('w', 'a', 1)
    mode = mode.replace('w+', 'r+')
    # possible values: r, w, a, r+, a+
    return mode 
Example #20
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example #21
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def get_path_uid(path):
    """
    Return path's uid.

    Does not follow symlinks:
        https://github.com/pypa/pip/pull/935#discussion_r5307003

    Placed this function in compat due to differences on AIX and
    Jython, that should eventually go away.

    :raises OSError: When path is a symlink or can't be read.
    """
    if hasattr(os, 'O_NOFOLLOW'):
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
        file_uid = os.fstat(fd).st_uid
        os.close(fd)
    else:  # AIX and Jython
        # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
        if not os.path.islink(path):
            # older versions of Jython don't have `os.fstat`
            file_uid = os.stat(path).st_uid
        else:
            # raise OSError for parity with os.O_NOFOLLOW above
            raise OSError(
                "%s is a symlink; Will not return uid for symlinks" % path
            )
    return file_uid 
Example #22
Source File: tarfile.py    From Python24 with MIT License 5 votes vote down vote up
def __init__(self, name, mode):
        mode = {
            "r": os.O_RDONLY,
            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
        }[mode]
        if hasattr(os, "O_BINARY"):
            mode |= os.O_BINARY
        self.fd = os.open(name, mode, 0o666) 
Example #23
Source File: tarfile.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, name, mode):
        mode = {
            "r": os.O_RDONLY,
            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
        }[mode]
        if hasattr(os, "O_BINARY"):
            mode |= os.O_BINARY
        self.fd = os.open(name, mode, 0o666) 
Example #24
Source File: remote_runner.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def recover_fds(self):
        """
        Helper function for reconnect to daemon/nohup process.
        """
        if self.r_pipe is None:
            self.recover_paths()
            self.w_pipe = os.open(self.w_path, os.O_WRONLY)
            self.r_pipe = os.open(self.r_path, os.O_RDONLY)
            self.stdin_pipe = os.open(self.stdin_path, os.O_WRONLY)
            self.stdout_pipe = os.open(self.stdout_path, os.O_RDONLY)
            self.stderr_pipe = os.open(self.stderr_path, os.O_RDONLY)
            self.msg = ms.Messenger(ms.StdIOWrapperIn(self.r_pipe),
                                    ms.StdIOWrapperOut(self.w_pipe)) 
Example #25
Source File: test_fileio.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testUnclosedFDOnException(self):
        class MyException(Exception): pass
        class MyFileIO(_FileIO):
            def __setattr__(self, name, value):
                if name == "name":
                    raise MyException("blocked setting name")
                return super(MyFileIO, self).__setattr__(name, value)
        fd = os.open(__file__, os.O_RDONLY)
        self.assertRaises(MyException, MyFileIO, fd)
        os.close(fd)  # should not raise OSError(EBADF) 
Example #26
Source File: terminal.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _get_terminal_size_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            import struct
            cr = struct.unpack(
                'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
        except (struct.error, IOError):
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except OSError:
            pass
    if not cr or cr == (0, 0):
        try:
            from os import environ as env
            cr = (env['LINES'], env['COLUMNS'])
        except (ValueError, KeyError):
            return None
    return int(cr[1]), int(cr[0]) 
Example #27
Source File: test_posix.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_fdopen_keeps_fd_open_on_errors(self):
        fd = os.open(test_support.TESTFN, os.O_RDONLY)
        self.assertRaises(OSError, posix.fdopen, fd, 'w')
        os.close(fd) # fd should not be closed. 
Example #28
Source File: test_posix.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_fdopen_directory(self):
        try:
            fd = os.open('.', os.O_RDONLY)
            self.addCleanup(os.close, fd)
        except OSError as e:
            self.assertEqual(e.errno, errno.EACCES)
            self.skipTest("system cannot open directories")
        with self.assertRaises(IOError) as cm:
            os.fdopen(fd, 'r')
        self.assertEqual(cm.exception.errno, errno.EISDIR) 
Example #29
Source File: test_posix.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def fdopen_helper(self, *args):
        fd = os.open(test_support.TESTFN, os.O_RDONLY)
        fp2 = posix.fdopen(fd, *args)
        fp2.close() 
Example #30
Source File: tarfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, name, mode):
        mode = {
            "r": os.O_RDONLY,
            "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
        }[mode]
        if hasattr(os, "O_BINARY"):
            mode |= os.O_BINARY
        self.fd = os.open(name, mode, 0o666)