Python os.strerror() Examples

The following are 30 code examples for showing how to use os.strerror(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: oscrypto   Author: wbond   File: util.py    License: MIT License 6 votes vote down vote up
def _extract_error():
    """
    Extracts the last OS error message into a python unicode string

    :return:
        A unicode string error message
    """

    error_num = errno()

    try:
        error_string = os.strerror(error_num)
    except (ValueError):
        return str_cls(error_num)

    if isinstance(error_string, str_cls):
        return error_string

    return _try_decode(error_string) 
Example 2
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example 3
Project: tornado-zh   Author: tao12345666333   File: simple_httpclient_test.py    License: MIT License 6 votes vote down vote up
def test_connection_refused(self):
        cleanup_func, port = refusing_port()
        self.addCleanup(cleanup_func)
        with ExpectLog(gen_log, ".*", required=False):
            self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop)
            response = self.wait()
        self.assertEqual(599, response.code)

        if sys.platform != 'cygwin':
            # cygwin returns EPERM instead of ECONNREFUSED here
            contains_errno = str(errno.ECONNREFUSED) in str(response.error)
            if not contains_errno and hasattr(errno, "WSAECONNREFUSED"):
                contains_errno = str(errno.WSAECONNREFUSED) in str(response.error)
            self.assertTrue(contains_errno, response.error)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(response.error),
                            response.error) 
Example 4
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example 5
Project: olympe   Author: Parrot-Developers   File: pomp_loop_thread.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_fd_to_loop(self, fd, cb, fd_events, userdata=None):
        if cb is None:
            self.logger.info(
                "Cannot add fd '{}' to pomp loop without "
                "a valid callback function".format(fd)
            )
            return None
        self.fd_userdata[fd] = userdata
        userdata = ctypes.cast(
            ctypes.pointer(ctypes.py_object(userdata)), ctypes.c_void_p
        )
        self.c_fd_userdata[fd] = userdata
        self.pomp_fd_callbacks[fd] = od.pomp_fd_event_cb_t(cb)
        res = od.pomp_loop_add(
            self.pomp_loop,
            ctypes.c_int32(fd),
            od.uint32_t(int(fd_events)),
            self.pomp_fd_callbacks[fd],
            userdata
        )
        if res != 0:
            raise RuntimeError(
                "Cannot add fd '{}' to pomp loop: {} ({})".format(
                    fd, os.strerror(-res), res)
            ) 
Example 6
Project: olympe   Author: Parrot-Developers   File: pdraw.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unref(self):
        """
        This function decrements the reference counter of the underlying buffer(s)
        """
        try:
            res = od.vbuf_unref(self._buf)
            if res != 0:
                self.logger.error("vbuf_unref unpacked frame error: {} {} {}".format(
                    self._media_id,
                    os.strerror(-res),
                    ctypes.addressof(self._buf.contents)
                ))
        finally:
            if self._yuv_packed_buffer:
                res = od.vbuf_unref(self._yuv_packed_buffer)
                if res != 0:
                    self.logger.error("vbuf_unref packed frame error: {} {} {}".format(
                        self._media_id,
                        os.strerror(-res),
                        ctypes.addressof(self._buf.contents)
                    )) 
Example 7
Project: calibre-web   Author: janeczku   File: server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _make_gevent_unix_socket(self, socket_file):
        # the socket file must not exist prior to bind()
        if os.path.exists(socket_file):
            # avoid nuking regular files and symbolic links (could be a mistype or security issue)
            if os.path.isfile(socket_file) or os.path.islink(socket_file):
                raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file)
            os.remove(socket_file)

        unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX)
        self.unix_socket_file = socket_file

        # ensure current user and group have r/w permissions, no permissions for other users
        # this way the socket can be shared in a semi-secure manner
        # between the user running calibre-web and the user running the fronting webserver
        os.chmod(socket_file, 0o660)

        return unix_sock 
Example 8
Project: pi-timolo   Author: pageauc   File: metadata.py    License: MIT License 6 votes vote down vote up
def _instantiate_image(self, filename):
        """Instanciate the exiv2 image.

        Args:
        filename -- str(path to an image file)
        """
        # This method is meant to be overridden in unit tests to easily replace
        # the internal image reference by a mock.
        if not os.path.exists(filename) or not os.path.isfile(filename):
            raise IOError(ENOENT, os.strerror(ENOENT), filename)

        # Remember the reference timestamps before doing any access to the file
        stat = os.stat(filename)
        self._atime = stat.st_atime
        self._mtime = stat.st_mtime
        return libexiv2python._Image(filename) 
Example 9
Project: workload-collocation-agent   Author: intel   File: perf.py    License: Apache License 2.0 6 votes vote down vote up
def _create_file_from_fd(pfd):
    """Validates file description and creates a file-like object"""
    # -1 is returned on error: http://man7.org/linux/man-pages/man2/open.2.html#RETURN_VALUE
    if pfd == -1:
        INVALID_ARG_ERRNO = 22
        errno = ctypes.get_errno()
        if errno == INVALID_ARG_ERRNO:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}. '
                                         'For cgroup based perf counters it may indicate there is '
                                         'no enough hardware counters for measure all metrics!'
                                         'If traceback shows problem in perf_uncore '
                                         'it could be problem with PERF_FORMAT_GROUP in'
                                         'perf_event_attr structure for perf_event_open syscall.'
                                         'Older kernel cannot handle with extended format group.'
                                         'Kernel cannot be 3.10.0-862.el7.x86_64 or lower.'
                                         ''.format(errno, os.strerror(errno)))
        else:
            raise UnableToOpenPerfEvents('Invalid perf event file descriptor: {}, {}.'
                                         .format(errno, os.strerror(errno)))
    return os.fdopen(pfd, 'rb') 
Example 10
Project: workload-collocation-agent   Author: intel   File: cgroups_allocations.py    License: Apache License 2.0 6 votes vote down vote up
def _migrate_page_call(pid, max_node, old_nodes, new_node) -> int:
    """Wrapper on migrate_pages function using libc syscall"""

    pid = int(pid)
    max = ctypes.c_ulong(max_node + 1)
    old = ctypes.pointer(ctypes.c_ulong(old_nodes))
    new = ctypes.pointer(ctypes.c_ulong(new_node))

    # Example memory_migrate(256, pid, 5, 13 -> b'1101', 2 -> b'0010')
    result = LIBC.syscall(NR_MIGRATE_PAGES, pid, max, old, new)

    if result == -1:
        errno = ctypes.get_errno()
        raise UnableToMigratePages('Unable to migrate pages: {}, {}.'
                                   .format(errno, os.strerror(errno)))
    log.log(TRACE, 'Number of not moved pages (return from migrate_pages syscall): %d', result)
    return result 
Example 11
def monotonicTime(self, asSeconds = True):
        t = timespec()
        if self.clock_gettime(rmMonotonicTime.CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
            errno_ = ctypes.get_errno()
            if self.fallback:
                log.info("Monotonic Clock Error ! Reverting to time.time() fallback")
                return self.monotonicFallback(asSeconds)
            else:
                raise OSError(errno_, os.strerror(errno_))

        if asSeconds:
            return t.tv_sec

        return t.tv_sec + t.tv_nsec * 1e-9


#-----------------------------------------------------------------------------------------------
#
#
# 
Example 12
Project: kano-toolset   Author: KanoComputing   File: timeout.py    License: GNU General Public License v2.0 6 votes vote down vote up
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator 
Example 13
Project: benchexec   Author: sosy-lab   File: libc.py    License: Apache License 2.0 6 votes vote down vote up
def _check_errno(result, func, arguments):
    assert func.restype in [c_int, c_void_p]
    if (func.restype == c_int and result == -1) or (
        func.restype == c_void_p and c_void_p(result).value == c_void_p(-1).value
    ):
        errno = _ctypes.get_errno()
        try:
            func_name = func.__name__
        except AttributeError:
            func_name = "__unknown__"
        msg = (
            func_name
            + "("
            + ", ".join(map(str, arguments))
            + ") failed: "
            + _os.strerror(errno)
        )
        raise OSError(errno, msg)
    return result


# off_t is a signed integer type required for mmap.
# In my tests it is equal to long on both 32bit and 64bit x86 Linux. 
Example 14
Project: benchexec   Author: sosy-lab   File: test_runexecutor.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self, *args, **kwargs):
        try:
            container.execute_in_namespace(lambda: 0)
        except OSError as e:
            self.skipTest("Namespaces not supported: {}".format(os.strerror(e.errno)))

        dir_modes = kwargs.pop(
            "dir_modes",
            {
                "/": containerexecutor.DIR_READ_ONLY,
                "/home": containerexecutor.DIR_HIDDEN,
                "/tmp": containerexecutor.DIR_HIDDEN,
            },
        )

        self.runexecutor = RunExecutor(
            use_namespaces=True, dir_modes=dir_modes, *args, **kwargs
        ) 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_socketserver.py    License: Apache License 2.0 6 votes vote down vote up
def mocked_select_module(self):
        """Mocks the select.select() call to raise EINTR for first call"""
        old_select = select.select

        class MockSelect:
            def __init__(self):
                self.called = 0

            def __call__(self, *args):
                self.called += 1
                if self.called == 1:
                    # raise the exception on first call
                    raise select.error(errno.EINTR, os.strerror(errno.EINTR))
                else:
                    # Return real select value for consecutive calls
                    return old_select(*args)

        select.select = MockSelect()
        try:
            yield select.select
        finally:
            select.select = old_select 
Example 16
Project: opendevops   Author: opendevops-cn   File: simple_httpclient_test.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_connection_refused(self):
        cleanup_func, port = refusing_port()
        self.addCleanup(cleanup_func)
        with ExpectLog(gen_log, ".*", required=False):
            with self.assertRaises(socket.error) as cm:
                self.fetch("http://127.0.0.1:%d/" % port, raise_error=True)

        if sys.platform != "cygwin":
            # cygwin returns EPERM instead of ECONNREFUSED here
            contains_errno = str(errno.ECONNREFUSED) in str(cm.exception)
            if not contains_errno and hasattr(errno, "WSAECONNREFUSED"):
                contains_errno = str(errno.WSAECONNREFUSED) in str(  # type: ignore
                    cm.exception
                )
            self.assertTrue(contains_errno, cm.exception)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(cm.exception), cm.exception) 
Example 17
Project: nfcpy   Author: nfcpy   File: acr122.py    License: European Union Public License 1.1 6 votes vote down vote up
def ccid_xfr_block(self, data, timeout=0.1):
        """Encapsulate host command *data* into an PC/SC Escape command to
        send to the device and extract the chip response if received
        within *timeout* seconds.

        """
        frame = struct.pack("<BI5B", 0x6F, len(data), 0, 0, 0, 0, 0) + data
        self.transport.write(bytearray(frame))
        frame = self.transport.read(int(timeout * 1000))
        if not frame or len(frame) < 10:
            log.error("insufficient data for decoding ccid response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if frame[0] != 0x80:
            log.error("expected a RDR_to_PC_DataBlock")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if len(frame) != 10 + struct.unpack("<I", memoryview(frame)[1:5])[0]:
            log.error("RDR_to_PC_DataBlock length mismatch")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        return frame[10:] 
Example 18
Project: nfcpy   Author: nfcpy   File: acr122.py    License: European Union Public License 1.1 6 votes vote down vote up
def command(self, cmd_code, cmd_data, timeout):
        """Send a host command and return the chip response.

        """
        log.log(logging.DEBUG-1, "{} {}".format(self.CMD[cmd_code],
                                                hexlify(cmd_data).decode()))

        frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
        frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame

        frame = self.ccid_xfr_block(frame, timeout)
        if not frame or len(frame) < 4:
            log.error("insufficient data for decoding chip response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if not (frame[0] == 0xD5 and frame[1] == cmd_code + 1):
            log.error("received invalid chip response")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        if not (frame[-2] == 0x90 and frame[-1] == 0x00):
            log.error("received pseudo apdu with error status")
            raise IOError(errno.EIO, os.strerror(errno.EIO))
        return frame[2:-2] 
Example 19
Project: nfcpy   Author: nfcpy   File: transport.py    License: European Union Public License 1.1 6 votes vote down vote up
def read(self, timeout):
        if self.tty is not None:
            self.tty.timeout = max(timeout/1E3, 0.05)
            frame = bytearray(self.tty.read(6))
            if frame is None or len(frame) == 0:
                raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
            if frame.startswith(b"\x00\x00\xff\x00\xff\x00"):
                log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
                return frame
            LEN = frame[3]
            if LEN == 0xFF:
                frame += self.tty.read(3)
                LEN = frame[5] << 8 | frame[6]
            frame += self.tty.read(LEN + 1)
            log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
            return frame 
Example 20
Project: nfcpy   Author: nfcpy   File: pn53x.py    License: European Union Public License 1.1 6 votes vote down vote up
def __init__(self, chipset, logger):
        self.chipset = chipset
        self.log = logger

        try:
            chipset_communication = self.chipset.diagnose('line')
        except Chipset.Error:
            chipset_communication = False

        if chipset_communication is False:
            self.log.error("chipset communication test failed")
            raise IOError(errno.EIO, os.strerror(errno.EIO))

        # for line in self._print_ciu_register_page(0, 1, 2, 3):
        #     self.log.debug(line)

        # for addr in range(0, 0x03FF, 16):
        #     xram = self.chipset.read_register(*range(addr, addr+16))
        #     xram = ' '.join(["%02X" % x for x in xram])
        #     self.log.debug("0x%04X: %s", addr, xram) 
Example 21
Project: BinderFilter   Author: dxwu   File: test_socketserver.py    License: MIT License 6 votes vote down vote up
def mocked_select_module(self):
        """Mocks the select.select() call to raise EINTR for first call"""
        old_select = select.select

        class MockSelect:
            def __init__(self):
                self.called = 0

            def __call__(self, *args):
                self.called += 1
                if self.called == 1:
                    # raise the exception on first call
                    raise select.error(errno.EINTR, os.strerror(errno.EINTR))
                else:
                    # Return real select value for consecutive calls
                    return old_select(*args)

        select.select = MockSelect()
        try:
            yield select.select
        finally:
            select.select = old_select 
Example 22
Project: viewfinder   Author: viewfinderco   File: iostream.py    License: Apache License 2.0 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            gen_log.warning("Connect error on fd %d: %s",
                            self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        self._connecting = False 
Example 23
Project: viewfinder   Author: viewfinderco   File: simple_httpclient_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_connection_refused(self):
        server_socket, port = bind_unused_port()
        server_socket.close()
        with ExpectLog(gen_log, ".*", required=False):
            self.http_client.fetch("http://localhost:%d/" % port, self.stop)
            response = self.wait()
        self.assertEqual(599, response.code)

        if sys.platform != 'cygwin':
            # cygwin returns EPERM instead of ECONNREFUSED here
            self.assertTrue(str(errno.ECONNREFUSED) in str(response.error),
                            response.error)
            # This is usually "Connection refused".
            # On windows, strerror is broken and returns "Unknown error".
            expected_message = os.strerror(errno.ECONNREFUSED)
            self.assertTrue(expected_message in str(response.error),
                            response.error) 
Example 24
Project: multibootusb   Author: mbusb   File: _errorcheckers.py    License: GNU General Public License v2.0 5 votes vote down vote up
def exception_from_errno(errnum):
    """Create an exception from ``errnum``.

    ``errnum`` is an integral error number.

    Return an exception object appropriate to ``errnum``.

    """
    exception = ERRNO_EXCEPTIONS.get(errnum)
    errorstr = os.strerror(errnum)
    if exception is not None:
        return exception(errorstr)
    else:
        return EnvironmentError(errnum, errorstr) 
Example 25
Project: smbprotocol   Author: jborean93   File: exceptions.py    License: MIT License 5 votes vote down vote up
def __init__(self, ntstatus, filename, filename2=None):
        self.ntstatus = ntstatus
        self.filename2 = to_native(filename2) if filename2 else None

        ntstatus_name = 'STATUS_UNKNOWN'
        for name, val in vars(NtStatus).items():
            if ntstatus == val:
                ntstatus_name = name
                break

        error_details = {
            NtStatus.STATUS_OBJECT_NAME_NOT_FOUND: errno.ENOENT,
            NtStatus.STATUS_OBJECT_PATH_NOT_FOUND: errno.ENOENT,
            NtStatus.STATUS_OBJECT_NAME_COLLISION: errno.EEXIST,
            NtStatus.STATUS_PRIVILEGE_NOT_HELD: (errno.EACCES, "Required privilege not held"),
            NtStatus.STATUS_SHARING_VIOLATION: (errno.EPERM, "The process cannot access the file because it is being "
                                                             "used by another process"),
            NtStatus.STATUS_NOT_A_REPARSE_POINT: (errno.EINVAL, "The file or directory is not a reparse point"),
            NtStatus.STATUS_FILE_IS_A_DIRECTORY: errno.EISDIR,
            NtStatus.STATUS_NOT_A_DIRECTORY: errno.ENOTDIR,
            NtStatus.STATUS_DIRECTORY_NOT_EMPTY: errno.ENOTEMPTY,
            NtStatus.STATUS_END_OF_FILE: getattr(errno, 'ENODATA', 120),  # Not present on py2 for Windows.
        }.get(ntstatus, (0, "Unknown NtStatus error returned '%s'" % ntstatus_name))

        if not isinstance(error_details, tuple):
            error_details = (error_details, os.strerror(error_details))

        super(SMBOSError, self).__init__(error_details[0], error_details[1], to_native(filename)) 
Example 26
Project: smbprotocol   Author: jborean93   File: exceptions.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        msg = "[Error {0}] [NtStatus 0x{1}] {2}: '{3}'".format(self.errno, format(self.ntstatus, 'x').zfill(8),
                                                               self.strerror, self.filename)
        if self.filename2:
            msg += " -> '%s'" % self.filename2

        return msg 
Example 27
Project: ANGRYsearch   Author: DoTheEvo   File: scandir.py    License: GNU General Public License v2.0 5 votes vote down vote up
def posix_error(filename):
        errno = ctypes.get_errno()
        exc = OSError(errno, strerror(errno))
        exc.filename = filename
        return exc 
Example 28
Project: calmjs   Author: calmjs   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def raise_os_error(_errno, path=None):
    """
    Helper for raising the correct exception under Python 3 while still
    being able to raise the same common exception class in Python 2.7.
    """

    msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno)
    raise OSError(_errno, msg) 
Example 29
Project: rtp_cluster   Author: sippy   File: clock_dtime.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clock_getdtime(type):
    t = timespec()
    if clock_gettime(type, ctypes.pointer(t)) != 0:
        errno_ = ctypes.get_errno()
        raise OSError(errno_, os.strerror(errno_))
    return float(t.tv_sec) + float(t.tv_nsec * 1e-09) 
Example 30
Project: recipes-py   Author: luci   File: fileutil.py    License: Apache License 2.0 5 votes vote down vote up
def _EnsureDir(mode, dest):
  if not os.path.isdir(dest):
    if os.path.exists(dest):
      raise OSError(errno.EEXIST, os.strerror(errno.EEXIST))
    os.makedirs(dest, mode)