我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.EBADF。
def unregister(self, fileobj): """ Unregister a file object from being monitored. """ try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) # Getting the fileno of a closed socket on Windows errors with EBADF. except socket.error as e: # Platform-specific: Windows. if e.errno != errno.EBADF: raise else: for key in self._fd_to_key.values(): if key.fileobj is fileobj: self._fd_to_key.pop(key.fd) break else: raise KeyError("{0!r} is not registered".format(fileobj)) return key
def write(self,data): self._check_closed() if self.mode != WRITE: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") if self.fileobj is None: raise ValueError, "write() on closed GzipFile object" # Convert data type if called by io.BufferedWriter. if isinstance(data, memoryview): data = data.tobytes() if len(data) > 0: self.size = self.size + len(data) self.crc = zlib.crc32(data, self.crc) & 0xffffffffL self.fileobj.write( self.compress.compress(data) ) self.offset += len(data) return len(data)
def __init__(self, fh, map=None, maxdata=None, ignore_broken_pipe=False, logger=None, **obsopt): """Wrap a dispatcher around the passed filehandle. If `ignore_broken_pipe` is `True`, an `EPIPE` or `EBADF` error will call `handle_close()` instead of `handle_expt()`. Useful when broken pipes should be handled quietly. `logger` is a logger which will be used to log unusual exceptions; otherwise, they will be printed to stderr. """ self.maxdata = maxdata if maxdata else self.pipe_maxdata self.__logger = logger if ignore_broken_pipe: self.__ignore_errno = [EPIPE, EBADF] else: self.__ignore_errno = [] self.__filehandle = fh # Check for overduplication of the file descriptor and close the extra fddup = os.dup(fh.fileno()) file_dispatcher.__init__(self, fddup, map=map) if (self._fileno != fddup): os.close (fddup) Observable.__init__(self, **obsopt)
def read_from_fd(self): try: chunk = os.read(self.fd, self.read_chunk_size) except (IOError, OSError) as e: if errno_from_exception(e) in _ERRNO_WOULDBLOCK: return None elif errno_from_exception(e) == errno.EBADF: # If the writing half of a pipe is closed, select will # report it as readable but reads will fail with EBADF. self.close(exc_info=True) return None else: raise if not chunk: self.close() return None return chunk
def kill_cmd(self): if self.cmd_pid > 1: try: os.close(self.cmd_fd) except OSError, e: if e.errno == errno.EBADF: pass # already closed else: raise e try: os.kill(self.cmd_pid, signal.SIGKILL) os.waitpid(self.cmd_pid, 0) except OSError, e: if e.errno not in [errno.ECHILD, errno.ESRCH]: raise Exception('unhandled errno: %d' % e.errno) self.cmd_pid = -1
def _kill_ssh(self): if self.ssh_pid > 1: try: os.kill(self.ssh_pid, signal.SIGTERM) os.waitpid(self.ssh_pid, 0) except OSError, e: if e.errno not in [errno.ECHILD, errno.ESRCH]: raise Exception('unhandled errno: %d' % e.errno) self.self_pid = -1 try: os.close(self.ssh_fd) except OSError, e: if e.errno == errno.EBADF: pass # already closed else: print 'WHAT?', e raise e
def close_fds(self, exclude): if type(exclude) != list: raise Exception('exclude is not a list: %s' % exclude) for i in exclude: if type(i) != int: raise Exception('exclude is not a list of int: %s' % exclude) # close all file descriptors except 0,1,2, whatever file descriptor is # connected to /dev/ptmx, and whatever the subclass wants to keep open. exclude.extend([0,1,2]) for fd in self.list_fds().keys(): if fd in exclude: continue try: os.close(fd) except OSError, e: if e.errno == errno.EBADF: continue raise
def daemonize(): # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16 if os.fork(): # launch child and... os._exit(0) # kill off parent os.setsid() if os.fork(): # launch child and... os._exit(0) # kill off parent again. os.umask(077) null=os.open('/dev/null', os.O_RDWR) for i in range(3): try: os.dup2(null, i) except OSError, e: if e.errno != errno.EBADF: raise os.close(null)
def closed(self): global old log.msg('closed %s' % self) log.msg(repr(self.conn.channels)) if not options['nocache']: # fork into the background if os.fork(): if old: fd = sys.stdin.fileno() tty.tcsetattr(fd, tty.TCSANOW, old) if (options['command'] and options['tty']) or \ not options['notty']: signal.signal(signal.SIGWINCH, signal.SIG_DFL) os._exit(0) os.setsid() for i in range(3): try: os.close(i) except OSError, e: import errno if e.errno != errno.EBADF: raise
def write(self, data): """ Writes (sends) the specified bytes to the connected peer. :param data: the data to send. """ if self._socket is None: raise ConnectionResetError() # TODO Timeout may be an issue when sending the data, Changed in v3.5: # The socket timeout is now the maximum total duration to send all data. try: self._socket.sendall(data) except socket.timeout as e: raise TimeoutError() from e except BrokenPipeError: self._raise_connection_reset() except OSError as e: if e.errno == errno.EBADF: self._raise_connection_reset() else: raise
def write(self,data): self._check_closed() if self.mode != WRITE: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") if self.fileobj is None: raise ValueError, "write() on closed GzipFile object" # Convert data type if called by io.BufferedWriter. if isinstance(data, memoryview): data = data.tobytes() if len(data) > 0: self.fileobj.write(self.compress.compress(data)) self.size += len(data) self.crc = zlib.crc32(data, self.crc) & 0xffffffffL self.offset += len(data) return len(data)
def wait(io, timeout=None, timeout_exc=timeout('timed out')): """Block the current greenlet until *io* is ready. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ assert io.callback is None, 'This socket is already used by another greenlet: %r' % (io.callback, ) if timeout is not None: timeout = Timeout.start_new(timeout, timeout_exc) try: return get_hub().wait(io) finally: if timeout is not None: timeout.cancel() # rename "io" to "watcher" because wait() works with any watcher
def _wait(self, watcher, timeout_exc=timeout('timed out')): """Block the current greenlet until *watcher* has pending events. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ assert watcher.callback is None, 'This socket is already used by another greenlet: %r' % (watcher.callback, ) if self.timeout is not None: timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False) else: timeout = None try: self.hub.wait(watcher) finally: if timeout is not None: timeout.cancel()
def wait_read(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None): """Block the current greenlet until *fileno* is ready to read. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ if event is None: event = core.read_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc)) else: assert event.callback == _wait_helper, event.callback assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, ) event.arg = (getcurrent(), timeout_exc) event.add(timeout) try: switch_result = get_hub().switch() assert event is switch_result, 'Invalid switch into wait_read(): %r' % (switch_result, ) finally: event.cancel() event.arg = None
def wait_write(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None): """Block the current greenlet until *fileno* is ready to write. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ if event is None: event = core.write_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc)) else: assert event.callback == _wait_helper, event.callback assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, ) event.arg = (getcurrent(), timeout_exc) event.add(timeout) try: switch_result = get_hub().switch() assert event is switch_result, 'Invalid switch into wait_write(): %r' % (switch_result, ) finally: event.arg = None event.cancel()
def recv(self, *args): sock = self._sock # keeping the reference so that fd is not closed during waiting while True: try: return sock.recv(*args) except error, ex: if ex[0] == EBADF: return '' if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise # QQQ without clearing exc_info test__refcount.test_clean_exit fails sys.exc_clear() try: wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event) except error, ex: if ex[0] == EBADF: return '' raise
def recv_into(self, *args): sock = self._sock while True: try: return sock.recv_into(*args) except error, ex: if ex[0] == EBADF: return 0 if ex[0] != EWOULDBLOCK or self.timeout == 0.0: raise sys.exc_clear() try: wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event) except error, ex: if ex[0] == EBADF: return 0 raise
def send(self, data, flags=0, timeout=timeout_default): sock = self._sock if timeout is timeout_default: timeout = self.timeout try: return sock.send(data, flags) except error, ex: if ex[0] != EWOULDBLOCK or timeout == 0.0: raise sys.exc_clear() try: wait_write(sock.fileno(), timeout=timeout, event=self._write_event) except error, ex: if ex[0] == EBADF: return 0 raise try: return sock.send(data, flags) except error, ex2: if ex2[0] == EWOULDBLOCK: return 0 raise
def wait(self, timeout): try: self.notify() ret = select.select(self.sockets, [], self.PIPE, timeout) if ret[0]: return ret[0] except select.error as e: if e.args[0] == errno.EINTR: return self.sockets if e.args[0] == errno.EBADF: if self.nr < 0: return self.sockets else: raise StopWaiting raise
def close_file_descriptor_if_open(fd): """ Close a file descriptor if already open. :param fd: The file descriptor to close. :return: ``None``. Close the file descriptor `fd`, suppressing an error in the case the file was not open. """ try: os.close(fd) except EnvironmentError as exc: if exc.errno == errno.EBADF: # File descriptor was not open. pass else: error = DaemonOSEnvironmentError( "Failed to close file descriptor {fd:d} ({exc})".format( fd=fd, exc=exc)) raise error
def unregister(self, fileobj): """ Unregister a file object from being monitored. """ try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) # Getting the fileno of a closed socket on Windows errors with EBADF. except socket.error as err: if err.errno != errno.EBADF: raise else: for key in self._fd_to_key.values(): if key.fileobj is fileobj: self._fd_to_key.pop(key.fd) break else: raise KeyError("{0!r} is not registered".format(fileobj)) return key
def wait_readwrite(fileno, timeout=None, timeout_exc=timeout('timed out'), event=None): """Block the current greenlet until *fileno* is ready to read or write. If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed. By default *timeout_exc* is ``socket.timeout('timed out')``. If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``. """ if event is None: event = core.readwrite_event(fileno, _wait_helper, timeout, (getcurrent(), timeout_exc)) else: assert event.callback == _wait_helper, event.callback assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, ) event.arg = (getcurrent(), timeout_exc) event.add(timeout) try: switch_result = get_hub().switch() assert event is switch_result, 'Invalid switch into wait_readwrite(): %r' % (switch_result, ) finally: event.arg = None event.cancel()
def write(self,data): self._check_closed() if self.mode != WRITE: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") if self.fileobj is None: raise ValueError("write() on closed GzipFile object") # Convert data type if called by io.BufferedWriter. if isinstance(data, memoryview): data = data.tobytes() if len(data) > 0: self.size = self.size + len(data) self.crc = zlib.crc32(data, self.crc) & 0xffffffff self.fileobj.write( self.compress.compress(data) ) self.offset += len(data) return len(data)