コード例 #1
0
def recvfrag_with_timeout(sock, timeout_seconds=None):
	if _select and timeout_seconds:
		rlist, wlist, xlist=_select([sock],[],[], timeout_seconds)
		if not rlist:
			raise NoDataError

	header = sock.recv(4)
	if not header:
		raise NoDataError #somehow, we got a _select response but still no data
		
	if len(header) < 4:
		raise BrokenFragmentError
	x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
	    ord(header[2])<<8 | ord(header[3])
	last = ((x & 0x80000000L) != 0)
	n = int(x & 0x7fffffff)
	
	frag=''
	
	while(len(frag) < n):	
		if _select and timeout_seconds:
			rlist, wlist, xlist=_select([sock],[],[], timeout_seconds)
			if not rlist:
				raise BrokenFragmentError
			
		frag += sock.recv(n-len(frag))
				
	return last, frag
コード例 #2
0
ファイル: rpc.py プロジェクト: PatrykGala/pythonlabtools
def recvfrag_with_timeout(sock, timeout_seconds=None):
    # print "receiving from ", sock
    if _select and timeout_seconds:
        # print "Selecting with timeout...", timeout_seconds
        rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
        if not rlist:
            raise EOFError, "No header at all in recvfrag()"

    header = sock.recv(4)
    if len(header) < 4:
        raise EOFError
    x = long(ord(header[0])) << 24 | ord(header[1]) << 16 | \
        ord(header[2]) << 8 | ord(header[3])
    last = ((x & 0x80000000L) != 0)
    n = int(x & 0x7fffffff)

    frag = ''

    while (len(frag) < n):
        if _select and timeout_seconds:
            # print "Selecting with timeout...", timeout_seconds
            rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
            if not rlist:
                raise EOFError, "No data after header in recvfrag()"
        frag += sock.recv(n - len(frag))

    return last, frag
コード例 #3
0
def recvfrag_with_timeout(sock, timeout_seconds=None):
    if _select and timeout_seconds:
        rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
        if not rlist:
            raise NoDataError

    header = sock.recv(4)
    if not header:
        raise NoDataError  #somehow, we got a _select response but still no data

    if len(header) < 4:
        raise BrokenFragmentError
    x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
        ord(header[2])<<8 | ord(header[3])
    last = ((x & 0x80000000L) != 0)
    n = int(x & 0x7fffffff)

    frag = ''

    while (len(frag) < n):
        if _select and timeout_seconds:
            rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
            if not rlist:
                raise BrokenFragmentError

        frag += sock.recv(n - len(frag))

    return last, frag
コード例 #4
0
ファイル: rpc.py プロジェクト: pyridoxus/lab-tools
def recvfrag_with_timeout(sock, timeout_seconds=None):
    # print "receiving from ", sock
    if _select and timeout_seconds:
        # print "Selecting with timeout...", timeout_seconds
        rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
        if not rlist:
            raise EOFError, "No header at all in recvfrag()"

    header = sock.recv(4)
    if len(header) < 4:
        raise EOFError
    x = long(ord(header[0])) << 24 | ord(header[1]) << 16 | ord(header[2]) << 8 | ord(header[3])
    last = (x & 0x80000000L) != 0
    n = int(x & 0x7FFFFFFF)

    frag = ""

    while len(frag) < n:
        if _select and timeout_seconds:
            # print "Selecting with timeout...", timeout_seconds
            rlist, wlist, xlist = _select([sock], [], [], timeout_seconds)
            if not rlist:
                raise EOFError, "No data after header in recvfrag()"
        frag += sock.recv(n - len(frag))

    return last, frag
コード例 #5
0
ファイル: udev.py プロジェクト: 3v1n0/Solaar
def read(device_handle, bytes_count, timeout_ms=-1):
	"""Read an Input report from a HID device.

	:param device_handle: a device handle returned by open() or open_path().
	:param bytes_count: maximum number of bytes to read.
	:param timeout_ms: can be -1 (default) to wait for data indefinitely, 0 to
	read whatever is in the device's input buffer, or a positive integer to
	wait that many milliseconds.

	Input reports are returned to the host through the INTERRUPT IN endpoint.
	The first byte will contain the Report number if the device uses numbered
	reports.

	:returns: the data packet read, an empty bytes string if a timeout was
	reached, or None if there was an error while reading.
	"""
	assert device_handle
	timeout = None if timeout_ms < 0 else timeout_ms / 1000.0
	rlist, wlist, xlist = _select([device_handle], [], [device_handle], timeout)

	if xlist:
		assert xlist == [device_handle]
		raise IOError(_errno.EIO, 'exception on file descriptor %d' % device_handle)

	if rlist:
		assert rlist == [device_handle]
		data = _os.read(device_handle, bytes_count)
		assert data is not None
		assert isinstance(data, bytes), (repr(data), type(data))
		return data
	else:
		return b''
コード例 #6
0
ファイル: udev.py プロジェクト: doctor64/Solaar
def read(device_handle, bytes_count, timeout_ms=-1):
    """Read an Input report from a HID device.

    :param device_handle: a device handle returned by open() or open_path().
    :param bytes_count: maximum number of bytes to read.
    :param timeout_ms: can be -1 (default) to wait for data indefinitely, 0 to
    read whatever is in the device's input buffer, or a positive integer to
    wait that many milliseconds.

    Input reports are returned to the host through the INTERRUPT IN endpoint.
    The first byte will contain the Report number if the device uses numbered
    reports.

    :returns: the data packet read, an empty bytes string if a timeout was
    reached, or None if there was an error while reading.
    """
    assert device_handle
    timeout = None if timeout_ms < 0 else timeout_ms / 1000.0
    rlist, wlist, xlist = _select([device_handle], [], [device_handle],
                                  timeout)

    if xlist:
        assert xlist == [device_handle]
        raise IOError(_errno.EIO,
                      'exception on file descriptor %d' % device_handle)

    if rlist:
        assert rlist == [device_handle]
        data = _os.read(device_handle, bytes_count)
        assert data is not None
        assert isinstance(data, bytes), (repr(data), type(data))
        return data
    else:
        return b''
コード例 #7
0
def main():
    args = _parse_arguments()
    handle = _open(args)

    if interactive:
        print('.. Press ^C/^D to exit, or type hex bytes to write to the device.')

        import readline
        if args.history is None:
            import os.path
            args.history = os.path.join(os.path.expanduser('~'), '.hidconsole-history')
        try:
            readline.read_history_file(args.history)
        except Exception:
            # file may not exist yet
            pass

    try:
        from threading import Thread
        t = Thread(target=_continuous_read, args=(handle, ))
        t.daemon = True
        t.start()

        if interactive:
            # move the cursor at the bottom of the screen
            sys.stdout.write('\033[300B')  # move cusor at most 300 lines down, don't scroll

        while t.is_alive():
            line = read_packet(prompt)
            line = line.strip().replace(' ', '')
            # print ("line", line)
            if not line:
                continue

            data = _validate_input(line, args.hidpp)
            if data is None:
                continue

            _print('<<', data)
            _hid.write(handle, data)
            # wait for some kind of reply
            if args.hidpp and not interactive:
                rlist, wlist, xlist = _select([handle], [], [], 1)
                if data[1:2] == b'\xFF':
                    # the receiver will reply very fast, in a few milliseconds
                    time.sleep(0.010)
                else:
                    # the devices might reply quite slow
                    time.sleep(0.700)
    except EOFError:
        if interactive:
            print('')
        else:
            time.sleep(1)

    finally:
        print('.. Closing handle %r' % handle)
        _hid.close(handle)
        if interactive:
            readline.write_history_file(args.history)
コード例 #8
0
ファイル: thread_io.py プロジェクト: rawler/bhindex
 def send_within(self, seconds, data):
     deadline = time() + seconds
     while len(data):
         wait = deadline - time()
         if wait <= 0 or _select((), (self,), (), wait) == ([], [], []):
             raise _socket.timeout("Timed out within %d" % seconds)
         sent = self.send(data)
         data = data[sent:]
コード例 #9
0
ファイル: utils.py プロジェクト: asteven/butter
    def wait(self, timeout=None):
        if not self._events:
            # we use select here as the FD may be opened in non blocking mode
            rd, _, _ =_select([self], [], [], timeout)
            if self not in rd:
                raise TimeoutError("No event occured")

        return self.read_event()
コード例 #10
0
ファイル: _compat.py プロジェクト: Djalma1991/TriviaMVA
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except select_error as e:
             if e.args[0] == errno.EINTR:
                 continue
             raise
コード例 #11
0
ファイル: _compat.py プロジェクト: marc1n/redis-py
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except select_error as e:
             if e.args[0] == errno.EINTR:
                 continue
             raise
コード例 #12
0
    def select(rlist, wlist, xlist, timeout=None):
        #runtime patching for select function
        try:
            for i in rlist + wlist + xlist:
                assert not i.using_iocp
        except AssertionError:
            raise IOCPError, "can't select a iocp registered socket."

        return _select._select(rlist, wlist, xlist, timeout)
コード例 #13
0
ファイル: __init__.py プロジェクト: elvisw/python-iocp
 def select(rlist, wlist, xlist, timeout=None):
     #runtime patching for select function
     try:
         for i in rlist + wlist + xlist:
             assert not i.using_iocp
     except AssertionError:
         raise IOCPError, "can't select a iocp registered socket."
     
     return _select._select(rlist, wlist, xlist, timeout)
コード例 #14
0
ファイル: _compat.py プロジェクト: ZoeGeng/Art
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except InterruptedError as e:
             # Python 2 does not define InterruptedError, instead
             # try to catch an OSError with errno == EINTR == 4.
             if getattr(e, 'errno', None) == getattr(errno, 'EINTR', 4):
                 continue
             raise
コード例 #15
0
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except InterruptedError as e:
             # Python 2 does not define InterruptedError, instead
             # try to catch an OSError with errno == EINTR == 4.
             if getattr(e, 'errno', None) == getattr(errno, 'EINTR', 4):
                 continue
             raise
コード例 #16
0
ファイル: rpc.py プロジェクト: MbqIIB/pl1_testbench_framework
def recvfrag_with_timeout(sock, timeout_seconds=None):
	#print "receiving from ", sock
	if _select and timeout_seconds:
		#print "Selecting with timeout...", timeout_seconds
		rlist, wlist, xlist=_select([sock],[],[], timeout_seconds)
		if not rlist:
			raise EOFError, "No header at all in recvfrag()"

	header = sock.recv(4)
	if len(header) < 4:
		raise EOFError
	x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
	    ord(header[2])<<8 | ord(header[3])
コード例 #17
0
ファイル: rpc.py プロジェクト: pyridoxus/lab-tools
def sendfrag_with_timeout(sock, last, frag, timeout_seconds=None):
    x = len(frag)
    if last:
        x = x | 0x80000000L
    header = chr(int(x >> 24 & 0xFF)) + chr(int(x >> 16 & 0xFF)) + chr(int(x >> 8 & 0xFF)) + chr(int(x & 0xFF))
    block = header + frag
    n = len(block)
    nsent = 0
    while nsent < n:
        if _select and timeout_seconds:
            rlist, wlist, xlist = _select([], [sock], [], timeout_seconds)
            if not wlist:
                raise EOFError, "Blocked write in sendfrag()"
        nsent += sock.send(block[nsent:])
コード例 #18
0
def sendfrag_with_timeout(sock,  last, frag, timeout_seconds=None):
	x = len(frag)
	if last: x = x | 0x80000000L
	header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
		  chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
	block=header+frag
	n=len(block)
	nsent=0
	while(nsent<n):
		if _select and timeout_seconds:
			rlist, wlist, xlist=_select([],[sock],[], timeout_seconds)
			if not wlist:
				raise BlockedWriteError		
		nsent+=sock.send(block[nsent:])
コード例 #19
0
def sendfrag_with_timeout(sock, last, frag, timeout_seconds=None):
    x = len(frag)
    if last: x = x | 0x80000000L
    header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
       chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
    block = header + frag
    n = len(block)
    nsent = 0
    while (nsent < n):
        if _select and timeout_seconds:
            rlist, wlist, xlist = _select([], [sock], [], timeout_seconds)
            if not wlist:
                raise BlockedWriteError
        nsent += sock.send(block[nsent:])
コード例 #20
0
ファイル: core.py プロジェクト: eugene-eeo/scell
def select(rl, wl, timeout=None):
    """
    Returns the file objects ready for reading/writing
    from the read-list (*rl*) and write-list (*wl*),
    subject to *timeout* in seconds.

    :param rl: Objects interested in readability.
    :param wl: Objects interested in writability.
    :param timeout: Maximum blocking time in seconds,
        *None* for no timeout.
    """
    if not (rl or wl):
        return [], []
    readers, writers, _ = _select(rl, wl, (), timeout)
    return readers, writers
コード例 #21
0
 def hook(capsule, timeout=None):
     """Hook user's input between terminal and capsule, Get outputs."""
     is_readable, _, _ = _select([_input_from_user], [], [], 0)
     if is_readable:
         terminal_stdin = _input_from_user.readline().rstrip()
         try:
             _, capsule_stdout = capsule.write(
                 terminal_stdin,
                 timeout=timeout,
             )
         except Capsule.DEAD as dying_message:
             capsule_stdout = str(dying_message)
         return (terminal_stdin, capsule_stdout)
     else:
         try:
             capsule_stdout = capsule.read(timeout=timeout)
         except Capsule.DEAD as dying_message:
             capsule_stdout = str(dying_message)
         if capsule_stdout:
             return (None, capsule_stdout)
コード例 #22
0
def select(rlist,wlist,xlist,timeout):
    """
    Forward the capabilities of the standard select() for use with the Stream
    class. In the future, might be worth adding poll/epoll/kqueue support.
    """
    rdict,wdict = {},{}

    # Python builtin sockets are valid hashable objects
    for r in rlist:
        rdict[r.sock] = r

    for w in wlist:
        wdict[w.sock] = w

    rsl = [r.sock for r in rlist]
    wsl = [w.sock for w in wlist]

    rsl,wsl,esl = _select(rsl,wsl,[],timeout)

    return [rdict[r] for r in rsl], [wdict[w] for w in wsl],[]
コード例 #23
0
 def hook(capsule, timeout=None):
     """Hook user's input between terminal and capsule, Get outputs."""
     is_readable, _, _ = _select([_input_from_user], [], [], 0)
     if is_readable:
         terminal_stdin = _input_from_user.readline().rstrip()
         try:
             _, capsule_stdout = capsule.write(
                 terminal_stdin,
                 timeout=timeout,
             )
         except Capsule.DEAD as dying_message:
             capsule_stdout = str(dying_message)
         return (terminal_stdin, capsule_stdout)
     else:
         try:
             capsule_stdout = capsule.read(timeout=timeout)
         except Capsule.DEAD as dying_message:
             capsule_stdout = str(dying_message)
         if capsule_stdout:
             return (None, capsule_stdout)
コード例 #24
0
def empty_pipe():
    global _non_empty_pipe_count
    global _fd_read
    if _fd_write is None:
        init()

    pipe_empty = False
    while not pipe_empty:
        fd_r, _, _ = _select([_fd_read], [], [], 0)
        if _fd_read in fd_r:
            try:
                _os.read(_fd_read, MAX_MESSAGE_SIZE)
            except:
                break
            # logging.debug(f"read pipe before sending msg: {_os.read(_fd_read, MAX_MESSAGE_SIZE)}\n")
            _non_empty_pipe_count += 1
            if (_non_empty_pipe_count > 4):
                break
        else:
            pipe_empty = True
コード例 #25
0
ファイル: base.py プロジェクト: cyberj/pulsar
 def poll(self, timeout=None):
     readable, writeable, errors = _select(
         self.read_fds, self.write_fds, self.error_fds, timeout)
     return self.get_events(readable, writeable, errors)
コード例 #26
0
ファイル: hidconsole.py プロジェクト: Nek-/Solaar
def main():
	args = _parse_arguments()
	handle = _open(args.device, args.hidpp)

	if interactive:
		print (".. Press ^C/^D to exit, or type hex bytes to write to the device.")

		import readline
		if args.history is None:
			import os.path
			args.history = os.path.join(os.path.expanduser("~"), ".hidconsole-history")
		try:
			readline.read_history_file(args.history)
		except:
			# file may not exist yet
			pass

		# re-open stdout unbuffered
		try:
			sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
		except:
			# will fail in python3
			pass

	try:
		from threading import Thread
		t = Thread(target=_continuous_read, args=(handle,))
		t.daemon = True
		t.start()

		if interactive:
			# move the cursor at the bottom of the screen
			sys.stdout.write('\033[300B')  # move cusor at most 300 lines down, don't scroll

		while t.is_alive():
			line = read_packet(prompt)
			line = line.strip().replace(' ', '')
			# print ("line", line)
			if not line:
				continue

			data = _validate_input(line, args.hidpp)
			if data is None:
				continue

			_print("<<", data)
			hidapi.write(handle, data)
			# wait for some kind of reply
			if args.hidpp and not interactive:
				rlist, wlist, xlist = _select([handle], [], [], 1)
				if data[1:2] == b'\xFF':
					# the receiver will reply very fast, in a few milliseconds
					time.sleep(0.100)
				else:
					# the devices might reply quite slow
					time.sleep(1)
	except EOFError:
		if interactive:
			print ("")
		else:
			time.sleep(1)
	except Exception as e:
		print ('%s: %s' % (type(e).__name__, e))

	print (".. Closing handle %r" % handle)
	hidapi.close(handle)
	if interactive:
		readline.write_history_file(args.history)
コード例 #27
0
ファイル: utils.py プロジェクト: arkaitzj/python-butter
    def wait(self):
        # we use select here as the FD may be opened in non blocking mode
        _select([self.fileno()], [], [])

        return self.read_event()
コード例 #28
0
ファイル: rpc.py プロジェクト: MbqIIB/pl1_testbench_framework
			raise EOFError, "No header at all in recvfrag()"

	header = sock.recv(4)
	if len(header) < 4:
		raise EOFError
	x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
	    ord(header[2])<<8 | ord(header[3])
	last = ((x & 0x80000000L) != 0)
	n = int(x & 0x7fffffff)

	frag=''

	while(len(frag) < n):
		if _select and timeout_seconds:
			#print "Selecting with timeout...", timeout_seconds
			rlist, wlist, xlist=_select([sock],[],[], timeout_seconds)
			if not rlist:
				raise EOFError, "No data after header in recvfrag()"
		frag += sock.recv(n-len(frag))

	return last, frag


def recvrecord(sock, timeout_seconds=None):
	record = ''
	last = 0
	while not last:
		last, frag = recvfrag_with_timeout(sock, timeout_seconds)
		record = record + frag
	return record
コード例 #29
0
ファイル: _compat.py プロジェクト: AbdullahAli/redis-py
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except InterruptedError:
             continue
コード例 #30
0
 def select(rlist, wlist, xlist, timeout):
     while True:
         try:
             return _select(rlist, wlist, xlist, timeout)
         except InterruptedError:
             continue
コード例 #31
0
ファイル: greensock2.py プロジェクト: TheDunn/flex-pypy
def dispatcher_mainloop():
    global g_timers_mixed
    GreenletExit = greenlet.GreenletExit
    while 1:
        try:
            while g_active:
                #print 'active:', g_active[0]
                g_active.popleft().switch()
#                active.switch()
#                if active.dead:
#                    check_waiters(active)
#                    del active
            if g_timers:
                if g_timers_mixed:
                    heapify(g_timers)
                    g_timers_mixed = False
                activationtime, timer = g_timers[0]
                delay = activationtime - _time()
                if delay <= 0.0:
                    if timer.started:
                        heappop(g_timers)
                        #print 'timeout:', g
                        timer.finished = True
                        timer.g.switch()
#                        if timer.g.dead:
#                            check_waiters(timer.g)
                        continue
                    delay = 0.0
                timer.started = True
            else:
                check_dead_greenlets(g_iwtd)
                check_dead_greenlets(g_owtd)
                if not (g_iwtd or g_owtd):
                    # nothing to do, switch to the main greenlet
                    g_dispatcher.parent.switch()
                    continue
                delay = None

            #print 'selecting...', g_iwtd.keys(), g_owtd.keys(), delay
            iwtd, owtd, _ = _select(g_iwtd.keys(), g_owtd.keys(), [], delay)
            #print 'done'
            for s in owtd:
                if s in g_owtd:
                    d = g_owtd[s]
                    #print 'owtd:', d[0]
                    g = d.popleft()
                    if not d:
                        try:
                            del g_owtd[s]
                        except KeyError:
                            pass
                    g.switch(g_owtd)
#                    if g.dead:
#                        check_waiters(g)
            for s in iwtd:
                if s in g_iwtd:
                    d = g_iwtd[s]
                    #print 'iwtd:', d[0]
                    g = d.popleft()
                    if not d:
                        try:
                            del g_iwtd[s]
                        except KeyError:
                            pass
                    g.switch(g_iwtd)
#                    if g.dead:
#                        check_waiters(g)
        except GreenletExit:
            raise
        except:
            import sys
            g_dispatcher.parent.throw(*sys.exc_info())