Python os.O_NONBLOCK Examples

The following are 30 code examples for showing how to use os.O_NONBLOCK(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: multibootusb   Author: mbusb   File: monitor.py    License: GNU General Public License v2.0 6 votes vote down vote up
def start(self):
        """
        Start this monitor.

        The monitor will not receive events until this method is called. This
        method does nothing if called on an already started :class:`Monitor`.

        .. note::

           Typically you don't need to call this method. It is implicitly
           called by :meth:`poll()` and :meth:`__iter__()`.

        .. seealso:: :attr:`started`
        .. versionchanged:: 0.16
           This method does nothing if the :class:`Monitor` was already
           started.
        """
        if not self._started:
            self._libudev.udev_monitor_enable_receiving(self)
            # Force monitor FD into non-blocking mode
            pipe.set_fd_status_flag(self, os.O_NONBLOCK)
            self._started = True 
Example 2
Project: multibootusb   Author: mbusb   File: pipe.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _pipe2_by_pipe(flags):
    """A ``pipe2`` implementation using :func:`os.pipe`.

    ``flags`` is an integer providing the flags to ``pipe2``.

    .. warning::

       This implementation is not atomic!

    Return a pair of file descriptors ``(r, w)``.

    """
    fds = os.pipe()
    if flags & os.O_NONBLOCK != 0:
        for fd in fds:
            set_fd_status_flag(fd, os.O_NONBLOCK)
    if flags & O_CLOEXEC != 0:
        for fd in fds:
            set_fd_flag(fd, O_CLOEXEC)
    return fds 
Example 3
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example 4
Project: derplearning   Author: notkarol   File: joystick.py    License: MIT License 6 votes vote down vote up
def __connect(self):
        device_addr, hidraw_device, event_device = self.__find_device()
        if device_addr is None:
            return False
        self.__report_fd = os.open(hidraw_device, os.O_RDWR | os.O_NONBLOCK)
        self.__fd = FileIO(self.__report_fd, "rb+", closefd=False)
        self.__input_device = InputDevice(event_device)
        self.__input_device.grab()
        buf = bytearray(38)
        buf[0] = 0x02
        try:
            return bool(fcntl.ioctl(self.__fd, 3223734279, bytes(buf)))
        except:
            pass
        if self.recv():
            self.update_controller() 
Example 5
Project: raveberry   Author: raveberry   File: programs.py    License: 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 6
Project: marker   Author: pindexis   File: readchar.py    License: MIT License 6 votes vote down vote up
def read_char_no_blocking():
    ''' Read a character in nonblocking mode, if no characters are present in the buffer, return an empty string '''
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    old_flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    try:
        tty.setraw(fd, termios.TCSADRAIN)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK)
        return sys.stdin.read(1)
    except IOError as e:
        ErrorNumber = e[0]
        # IOError with ErrorNumber 11(35 in Mac)  is thrown when there is nothing to read(Resource temporarily unavailable)
        if (sys.platform.startswith("linux") and ErrorNumber != 11) or (sys.platform == "darwin" and ErrorNumber != 35):
            raise
        return ""
    finally:
        fcntl.fcntl(fd, fcntl.F_SETFL, old_flags)
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 
Example 7
Project: HyperGAN   Author: HyperGAN   File: cli.py    License: MIT License 6 votes vote down vote up
def train(self):
        i=0
        if(self.args.ipython):
            import fcntl
            fd = sys.stdin.fileno()
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        while((i < self.total_steps or self.total_steps == -1) and not self.gan.destroy):
            i+=1
            start_time = time.time()
            self.step()
            GlobalViewer.tick()

            if (self.args.save_every != None and
                self.args.save_every != -1 and
                self.args.save_every > 0 and
                i % self.args.save_every == 0):
                print(" |= Saving network")
                self.gan.save(self.save_file)
            if self.args.ipython:
                self.check_stdin()
            end_time = time.time() 
Example 8
Project: avocado-vt   Author: avocado-framework   File: virtio_console_guest.py    License: GNU General Public License v2.0 6 votes vote down vote up
def blocking(self, port, mode=False):
        """
        Set port function mode blocking/nonblocking

        :param port: port to set mode
        :param mode: False to set nonblock mode, True for block mode
        """
        fd = self._open([port])[0]

        try:
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            if not mode:
                fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
            else:
                fcntl.fcntl(fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)

        except Exception as inst:
            print("FAIL: Setting (non)blocking mode: " + str(inst))
            return

        if mode:
            print("PASS: set to blocking mode")
        else:
            print("PASS: set to nonblocking mode") 
Example 9
Project: BinderFilter   Author: dxwu   File: test_fcntl.py    License: MIT License 6 votes vote down vote up
def test_fcntl_bad_file(self):
        class F:
            def __init__(self, fn):
                self.fn = fn
            def fileno(self):
                return self.fn
        self.assertRaises(ValueError, fcntl.fcntl, -1, fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(ValueError, fcntl.fcntl, F(-1), fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(TypeError, fcntl.fcntl, 'spam', fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(TypeError, fcntl.fcntl, F('spam'), fcntl.F_SETFL, os.O_NONBLOCK)
        # Issue 15989
        self.assertRaises(ValueError, fcntl.fcntl, _testcapi.INT_MAX + 1,
                                                   fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(ValueError, fcntl.fcntl, F(_testcapi.INT_MAX + 1),
                                                   fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(ValueError, fcntl.fcntl, _testcapi.INT_MIN - 1,
                                                   fcntl.F_SETFL, os.O_NONBLOCK)
        self.assertRaises(ValueError, fcntl.fcntl, F(_testcapi.INT_MIN - 1),
                                                   fcntl.F_SETFL, os.O_NONBLOCK) 
Example 10
Project: abusehelper   Author: abusesa   File: tailbot.py    License: MIT License 6 votes vote down vote up
def follow_file(filename):
    while True:
        try:
            fd = os.open(filename, os.O_RDONLY | os.O_NONBLOCK)
        except OSError:
            yield None
            continue

        try:
            inode = os.fstat(fd).st_ino
            first = True

            while True:
                try:
                    stat = os.stat(filename)
                except OSError:
                    stat = None

                yield first, time.time(), fd
                if stat is None or inode != stat.st_ino:
                    break

                first = False
        finally:
            os.close(fd) 
Example 11
Project: Safejumper-for-Desktop   Author: proxysh   File: tuntap.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _openTunnel(self, name, mode):
        """
        Open the named tunnel using the given mode.

        @param name: The name of the tunnel to open.
        @type name: L{bytes}

        @param mode: Flags from L{TunnelFlags} with exactly one of
            L{TunnelFlags.IFF_TUN} or L{TunnelFlags.IFF_TAP} set.

        @return: A L{_TunnelDescription} representing the newly opened tunnel.
        """
        flags = (
            self._system.O_RDWR | self._system.O_CLOEXEC |
            self._system.O_NONBLOCK)
        config = struct.pack("%dsH" % (_IFNAMSIZ,), name, mode.value)
        fileno = self._system.open(_TUN_KO_PATH, flags)
        result = self._system.ioctl(fileno, _TUNSETIFF, config)
        return _TunnelDescription(fileno, result[:_IFNAMSIZ].strip(b'\x00')) 
Example 12
Project: Safejumper-for-Desktop   Author: proxysh   File: test_tuntap.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_startListeningOpensDevice(self):
        """
        L{TuntapPort.startListening} opens the tunnel factory character special
        device C{"/dev/net/tun"} and configures it as a I{tun} tunnel.
        """
        system = self.system
        self.port.startListening()
        tunnel = self.system.getTunnel(self.port)

        expected = (
            system.O_RDWR | system.O_CLOEXEC | system.O_NONBLOCK,
            b"tun0" + b"\x00" * (_IFNAMSIZ - len(b"tun0")),
            self.port.interface, False, True)
        actual = (
            tunnel.openFlags,
            tunnel.requestedName,
            tunnel.name, tunnel.blocking, tunnel.closeOnExec)
        self.assertEqual(expected, actual) 
Example 13
Project: pygdbmi   Author: cs01   File: gdbcontroller.py    License: MIT License 6 votes vote down vote up
def _make_non_blocking(file_obj):
    """make file object non-blocking
    Windows doesn't have the fcntl module, but someone on
    stack overflow supplied this code as an answer, and it works
    http://stackoverflow.com/a/34504971/2893090"""

    if USING_WINDOWS:
        LPDWORD = POINTER(DWORD)
        PIPE_NOWAIT = wintypes.DWORD(0x00000001)

        SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
        SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
        SetNamedPipeHandleState.restype = BOOL

        h = msvcrt.get_osfhandle(file_obj.fileno())

        res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
        if res == 0:
            raise ValueError(WinError())

    else:
        # Set the file status flag (F_SETFL) on the pipes to be non-blocking
        # so we can attempt to read from a pipe with no new data without locking
        # the program up
        fcntl.fcntl(file_obj, fcntl.F_SETFL, os.O_NONBLOCK) 
Example 14
Project: multibootusb   Author: mbusb   File: pipe.py    License: GNU General Public License v2.0 5 votes vote down vote up
def open(cls):
        """Open and return a new :class:`Pipe`.

        The pipe uses non-blocking IO."""
        source, sink = _PIPE2(os.O_NONBLOCK | O_CLOEXEC)
        return cls(source, sink) 
Example 15
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 5 votes vote down vote up
def lin_tun_alloc(self, dev, flags):
		try:
			tun = os.open(Interface.LINUX_CLONEDEV, os.O_RDWR|os.O_NONBLOCK, 0)
			ifr = struct.pack('16sH', dev, flags)
			fcntl.ioctl(tun, self.IOCTL_LINUX_TUNSETIFF, ifr)

		except IOError:
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example 16
Project: macops   Author: google   File: gmacpyutil.py    License: Apache License 2.0 5 votes vote down vote up
def SetFileNonBlocking(f, non_blocking=True):
  """Set non-blocking flag on a file object.

  Args:
    f: file
    non_blocking: bool, default True, non-blocking mode or not
  """
  flags = fcntl.fcntl(f.fileno(), fcntl.F_GETFL)
  if bool(flags & os.O_NONBLOCK) != non_blocking:
    flags ^= os.O_NONBLOCK
  fcntl.fcntl(f.fileno(), fcntl.F_SETFL, flags) 
Example 17
Project: tornado-zh   Author: tao12345666333   File: posix.py    License: MIT License 5 votes vote down vote up
def _set_nonblocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 18
Project: tornado-zh   Author: tao12345666333   File: twisted_test.py    License: MIT License 5 votes vote down vote up
def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 19
Project: tornado-zh   Author: tao12345666333   File: posix.py    License: MIT License 5 votes vote down vote up
def _set_nonblocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 20
Project: tornado-zh   Author: tao12345666333   File: twisted_test.py    License: MIT License 5 votes vote down vote up
def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 21
Project: qutebrowser   Author: qutebrowser   File: userscripts.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, filepath, parent=None):
        super().__init__(parent)
        self._filepath = filepath
        # We open as R/W so we never get EOF and have to reopen the pipe.
        # See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/
        # We also use os.open and os.fdopen rather than built-in open so we
        # can add O_NONBLOCK.
        # pylint: disable=no-member,useless-suppression
        fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK)
        # pylint: enable=no-member,useless-suppression
        self._fifo = os.fdopen(fd, 'r')
        self._notifier = QSocketNotifier(typing.cast(sip.voidptr, fd),
                                         QSocketNotifier.Read, self)
        self._notifier.activated.connect(  # type: ignore[attr-defined]
            self.read_line) 
Example 22
Project: qutebrowser   Author: qutebrowser   File: crashsignal.py    License: GNU General Public License v3.0 5 votes vote down vote up
def activate(self):
        """Set up signal handlers.

        On Windows this uses a QTimer to periodically hand control over to
        Python so it can handle signals.

        On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
        notified.
        """
        self._orig_handlers[signal.SIGINT] = signal.signal(
            signal.SIGINT, self.interrupt)
        self._orig_handlers[signal.SIGTERM] = signal.signal(
            signal.SIGTERM, self.interrupt)

        if utils.is_posix and hasattr(signal, 'set_wakeup_fd'):
            # pylint: disable=import-error,no-member,useless-suppression
            import fcntl
            read_fd, write_fd = os.pipe()
            for fd in [read_fd, write_fd]:
                flags = fcntl.fcntl(fd, fcntl.F_GETFL)
                fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
            self._notifier = QSocketNotifier(typing.cast(sip.voidptr, read_fd),
                                             QSocketNotifier.Read,
                                             self)
            self._notifier.activated.connect(  # type: ignore[attr-defined]
                self.handle_signal_wakeup)
            self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
            # pylint: enable=import-error,no-member,useless-suppression
        else:
            self._timer.start(1000)
            self._timer.timeout.connect(lambda: None)
        self._activated = True 
Example 23
Project: recruit   Author: Frank-qlu   File: _compat.py    License: Apache License 2.0 5 votes vote down vote up
def set_binary_mode(f):
            try:
                fileno = f.fileno()
            except Exception:
                pass
            else:
                flags = fcntl.fcntl(fileno, fcntl.F_GETFL)
                fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
            return f 
Example 24
Project: jbox   Author: jpush   File: util.py    License: MIT License 5 votes vote down vote up
def set_non_blocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
    fcntl.fcntl(fd, fcntl.F_SETFL, flags) 
Example 25
def __writeNotification(string):
        #log.info("NotifyCloud: %s" % string)
        try:
            if stat.S_ISFIFO(os.stat(RMNotification.__cloudClientControlFile).st_mode) > 0:
                fd = os.open(RMNotification.__cloudClientControlFile, os.O_WRONLY | os.O_NONBLOCK)
                try:
                    os.write(fd, string)
                    log.debug("Notified cloud client about change")
                except Exception, e:
                    log.debug("Can't notify cloud client about settings change %s", str(e))
                finally:
                    os.close(fd) 
Example 26
Project: py-uio   Author: mvduin   File: device.py    License: MIT License 5 votes vote down vote up
def __init__( self, path, blocking=True, parent=None ):
        path = Path( '/dev/uio', path )
        self.path = path

        flags = O_RDWR | O_CLOEXEC
        if not blocking:
            flags |= O_NONBLOCK # for irq_recv
        self._fd = os.open( str(path), flags )

        # check parent memory region (if any)
        if parent is not None:
            if isinstance( parent, Uio ):
                parent = parent.region()
            elif isinstance( parent, MemRegion ):
                raise TypeError

        # build path to sysfs dir for obtaining metadata
        dev = os.stat( self._fd ).st_rdev
        dev = '{0}:{1}'.format( os.major(dev), os.minor(dev) )
        self.syspath = Path('/sys/dev/char', dev).resolve()

        # enumerate memory regions
        # beware that if there are none, the dir is absent rather than empty
        self._regions = {}
        rgninfo = self.syspath/'maps'
        if rgninfo.is_dir():
            for info in rgninfo.iterdir():
                rgn = MemRegion.from_sysfs( self, info, parent )

                # allow lookup by index or (if available) by name
                self._regions[ rgn.index ] = rgn
                if rgn.name:
                    self._regions[ rgn.name ] = rgn 
Example 27
Project: asciimatics   Author: peterbrittain   File: terminal.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, height):
        super(Terminal, self).__init__(height, line_wrap=True, parser=AnsiTerminalParser())

        #Key definitions
        self._map = {}
        for k, v in [
            (Screen.KEY_LEFT, "kcub1"),
            (Screen.KEY_RIGHT, "kcuf1"),
            (Screen.KEY_UP, "kcuu1"),
            (Screen.KEY_DOWN, "kcud1"),
            (Screen.KEY_HOME, "khome"),
            (Screen.KEY_END, "kend"),
            (Screen.KEY_BACK, "kbs"),
        ]:
            self._map[k] = curses.tigetstr(v)
        self._map[Screen.KEY_TAB] = "\t".encode()

        # Open a pseudo TTY to control the interactive session.  Make it non-blocking.
        self._master, slave = pty.openpty()
        fl = fcntl.fcntl(self._master, fcntl.F_GETFL)
        fcntl.fcntl(self._master, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        # Start the shell and thread to pull data from it.
        self._shell = subprocess.Popen(["bash", "-i"], preexec_fn=os.setsid, stdin=slave, stdout=slave, stderr=slave)
        self._lock = threading.Lock()
        self._thread = threading.Thread(target=self._background)
        self._thread.daemon = True
        self._thread.start() 
Example 28
Project: pcocc   Author: cea-hpc   File: Misc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fake_signalfd(sigs):
    sig_r, sig_w = os.pipe()
    fcntl.fcntl(sig_w, fcntl.F_SETFL, os.O_NONBLOCK)
    for sig in sigs:
        def _fake_sigfd_handler(signum, frame):
            logging.debug("Signalfd handler injecting "
                          "event for signal %s", signum)
            os.write(sig_w, 'x')
        signal.signal(sig, _fake_sigfd_handler)
    return sig_r 
Example 29
Project: meddle   Author: glmcdona   File: asyncore.py    License: MIT License 5 votes vote down vote up
def __init__(self, fd, map=None):
            dispatcher.__init__(self, None, map)
            self.connected = True
            try:
                fd = fd.fileno()
            except AttributeError:
                pass
            self.set_file(fd)
            # set it to non-blocking mode
            flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
            flags = flags | os.O_NONBLOCK
            fcntl.fcntl(fd, fcntl.F_SETFL, flags) 
Example 30
Project: ironpython2   Author: IronLanguages   File: asyncore.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, fd, map=None):
            dispatcher.__init__(self, None, map)
            self.connected = True
            try:
                fd = fd.fileno()
            except AttributeError:
                pass
            self.set_file(fd)
            # set it to non-blocking mode
            flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
            flags = flags | os.O_NONBLOCK
            fcntl.fcntl(fd, fcntl.F_SETFL, flags)