def readline(self): """ Reads a single line from the Serial Port Pipe. """ if self.timeout > 0: start_time = time.time() total_num_bytes = 0 while (time.time() - start_time) < self.timeout: (pipeData, numBytes, unused) = win32pipe.PeekNamedPipe(self.handle, 4096) if numBytes > 0: # look for the line-end. if found, read up to (and including) the line-end # if never found and we time-out, just read everything available... lineEndIdx = pipeData.find('\n') if (lineEndIdx >= 0): numBytes = lineEndIdx + 1 break # if we did get some NEW bytes (but still no newline), reset the start-time # so that we don't prematurely give up if there's more data coming if numBytes > total_num_bytes: total_num_bytes = numBytes start_time = time.time() time.sleep(0.1) else: (pipeData, numBytes, unused) = win32pipe.PeekNamedPipe(self.handle, 4096) if numBytes > 0: data = win32file.ReadFile(self.handle, numBytes) line = data[1] else: line = '' return line
def receive_message(self, header=None, num_attempts=100): #TODO: deal with discarded messages while waiting for a specific header if not self.is_connected(): print("RLGYM ATTEMPTED TO RECEIVE MESSAGE WITH NO CONNECTION") return communication_exception_handler.BROKEN_PIPE_ERROR m = Message() received_message = Message() exception_code = None for i in range(num_attempts): try: code, msg_bytes = win32file.ReadFile( self._pipe, CommunicationHandler.RLGYM_DEFAULT_PIPE_SIZE) #This is the pywintypes.error object type. except BaseException as e: exception_code = communication_exception_handler.handle_exception( e) break msg_str = bytes.decode(msg_bytes) m.deserialize(msg_str) #Only deserialize valid messages. if header is None or header == m.header: received_message.deserialize(msg_str) # Peek the next message in the pipe to see if we've reached the end of new messages. data = win32pipe.PeekNamedPipe( self._pipe, CommunicationHandler.RLGYM_DEFAULT_PIPE_SIZE) if data[0] == b'': break #TODO: make sure users of this object deal with the null message response return received_message, exception_code
async def recieve_if_available(self) -> None: raw = b"" # Only recieve data if there is data available in the pipe while win32pipe.PeekNamedPipe(self.pipe_handle, 0)[1] != 0: raw += win32file.ReadFile(self.pipe_handle, 1024)[1] if raw == b"": return # Split the raw bytes into seperate messages if possible, add to queue for response in [r for r in raw.split(b"\n") if r != b""]: json_data = json.loads(str(response, "ascii")) result = json_data["result"] if isinstance(result, dict): # promises and subscriptions are basically two different things using the same format, separate them here if result["_type"] == "HELPER": # idk if this even happens ever self.incoming_queue["helper"].append(json_data) elif result["_type"] == "SUBSCRIPTION": if result["emitter"] == "STREAM": self.incoming_queue["subscription"].append(json_data) if result["emitter"] == "PROMISE": self.incoming_queue["promise"].append(json_data) elif result["_type"] == "EVENT": if result["emitter"] == "STREAM": self.incoming_queue["event"].append(json_data) if result["emitter"] == "PROMISE": self.incoming_queue["fulfilled_promise"].append( json_data) else: # the result is probably supposed to be a helper self.incoming_queue["helper"].append(json_data)
async def on_ready(): # this is probably not very good practice but it works so eh global mic global scenes # from my experience the microphone should have a source id that starts with wasapi_input_capture mic = await slobs.get_audio_source( key=(lambda s: s.source_id.startswith("wasapi_input_capture"))) scenes["desktop"] = await slobs.get_scene( key=(lambda s: s.name == "Desktop")) scenes["game"] = await slobs.get_scene( key=(lambda s: s.name == "Just Game")) try: print("Waiting for luamacros script...") win32pipe.ConnectNamedPipe(key_pipe, None) print("Successfully connected to luamacros script through named pipe.") while True: raw = b"" while win32pipe.PeekNamedPipe(key_pipe, 0)[1] != 0: raw += win32file.ReadFile(key_pipe, 1024)[1] for key in raw.split(b"\r\n"): # luamacros likes crlfs if key != b"": await on_key_press(str(key, "ascii")) await asyncio.sleep(0.1) except pywintypes.error as e: if e.winerror == 109: print("Luamacros script closed.") else: print("Error:", e.funcname, "-", e.strerror) finally: win32file.CloseHandle(key_pipe)
async def read(self, n=-1): (read, num_avail, num_message) = win32pipe.PeekNamedPipe(self._pipe, 0) if num_avail > 0: (error_code, output) = win32file.ReadFile(self._pipe, num_avail, None) return output await asyncio.sleep(0.01) return b""
def get_from_host(self): data, avail, bytes_left = win32pipe.PeekNamedPipe(self.pipe, 4096) logger.spam(f'data: {data} avail:{avail} bytes_left{bytes_left}') if avail > 0: resp = win32file.ReadFile(self.pipe, 4096) ret = resp[1] return ret else: return b''
def is_open(self): if self.__handler: try: win32pipe.PeekNamedPipe(self.__handler, 0) except Exception: self.close() return False return True return False
def _non_blocking_read_win32(self, handle): try: _, avail, _ = win32pipe.PeekNamedPipe(handle, 0) if avail > 0: _, buf = win32file.ReadFile(handle, avail, None) return buf except Exception, e: if e[0] not in (109, errno.ESHUTDOWN): # 109 == win32 ERROR_BROKEN_PIPE raise
def read_from_pipe(self): if sys.platform.startswith('win'): (read, num_avail, num_message) = win32pipe.PeekNamedPipe(self.pipe, 0) if num_avail > 0: (error_code, output) = win32file.ReadFile(self.pipe, num_avail, None) return output return "" else: return self.pipe.recv(1024)
def has_data(self): if self.__handler: try: (data, nAvail, nMessage) = win32pipe.PeekNamedPipe(self.__handler, 0) return nAvail > 0 except Exception: self.close() pass return False
def _non_blocking_read_win32(self, handle): try: _, avail, _ = win32pipe.PeekNamedPipe(handle, 0) if avail > 0: _, buf = win32file.ReadFile(handle, avail, None) return buf except Exception as error: # pylint: disable=broad-except # 109 == win32 ERROR_BROKEN_PIPE if error[0] not in (109, errno.ESHUTDOWN): raise return None
def _non_blocking_read_win32(self, handle): try: _, avail, _ = win32pipe.PeekNamedPipe(handle, 0) if avail > 0: _, buf = win32file.ReadFile(handle, avail, None) return buf except pywintypes.error as e: if e.winerror not in (winerror.ERROR_INVALID_FUNCTION, winerror.ERROR_BROKEN_PIPE, errno.ESHUTDOWN): raise return None
def peek(self): """Peek the pipe.""" try: (buf, avail, remain) = win32pipe.PeekNamedPipe(self.handle, 0) except Exception, why: # this may occur on exit debug('got Exception %s', why) info('closing debugger after failed PeekNamedPipe syscall') # the main thread is busy waiting on the select_event in the # asyncore poll loop, so it's ok to close the debugger in # this thread self.asyncobj.channel.close() return False
def peek(self): """Returns the number of bytes available for reading without blocking. @return A two values, the first the number of bytes, and the second, an error code. An error code of zero indicates there was no error. @rtype (int, int) """ result = win32pipe.PeekNamedPipe(self.__pipe_handle, 1024) if result: return result[1], 0 else: return 0, 1
def __readPipe(handle): try: (buffer, available, result) = win32pipe.PeekNamedPipe(handle, 0) except pywintypes.error as e: raise BrokenPipeError if result == -1: raise BrokenPipeError if available > 0: result, data = win32file.ReadFile(handle, available, None) if result < 0: raise BrokenPipeError return data
def read(self): if self.__handler: try: (read, nAvail, nMessage) = win32pipe.PeekNamedPipe(self.__handler, 0) if nAvail > 0: (err, data) = win32file.ReadFile(self.__handler, nAvail, None) if err == 0: return data except Exception: self.close() return False return None
def checkWork(self): numBytesRead = 0 finished = 0 while 1: try: buffer, bytesToRead, result = win32pipe.PeekNamedPipe(self.pipe, 1) # finished = (result == -1) if not bytesToRead: break hr, data = win32file.ReadFile(self.pipe, bytesToRead, None) numBytesRead += len(data) self.receivedCallback(data) except win32api.error: finished = 1 break if finished: self.cleanup() return numBytesRead
def readFileHandle(self): hr, data = win32file.ReadFile(self.fileHandle, self.BUFFER_SIZE) fulldata = data while True: try: buffer, bytesToRead, result = \ win32pipe.PeekNamedPipe(self.fileHandle, 0) except: pass if bytesToRead == 0: break if bytesToRead > self.BUFFER_SIZE: bytesToRead = self.BUFFER_SIZE hr, data = win32file.ReadFile(self.fileHandle, bytesToRead) fulldata += data return fulldata
def _peek(self): if self._closed: return False # Check if there is anything to read and read if available (read, nAvail, nMessage) = win32pipe.PeekNamedPipe(self._osfhandle, 0) if nAvail >= self._buffer_size: data = self._pipe.read(self._buffer_size) self._buffer += data # If there is read_async callback and buffer has some data, # send them right away if not self._waits_for_read is None and len(self._buffer) > 0: r = WinPopenReader.Results(self._buffer) self._buffer = "" callback, data = self._waits_for_read self._waits_for_read = None callback(self, r, *data) GLib.idle_add(self._peek) return False GLib.timeout_add_seconds(1, self._peek) return False
def readPipe(): hr, data = win32file.ReadFile(fileHandle, 4096) fulldata = data n = 1 while 1: try: buffer, bytesToRead, result = win32pipe.PeekNamedPipe( fileHandle, 0) except: pass if bytesToRead == 0: break print 'READING ', n if bytesToRead > 4096: bytesToRead = 4096 hr, data = win32file.ReadFile(fileHandle, bytesToRead) fulldata += data n += 1 time.sleep(0.01) print fulldata
def win32_read_stdfd(self): '''Alternative implementation of stdout/stderr non-blocking read for Windows For details see: http://code.activestate.com/recipes/440554/ http://msdn.microsoft.com/en-us/library/windows/desktop/aa365779(v=vs.85).aspx ''' assert self.subproc is not None if self.subproc.stdout is not None: while 1: x = msvcrt.get_osfhandle(self.subproc.stdout.fileno()) try: (read, nAvail, nMessage) = win32pipe.PeekNamedPipe(x, 0) except pywintypes.error, e: if e.winerror == winerror.ERROR_BROKEN_PIPE: break raise if nAvail > 4096: nAvail = 4096 if nAvail == 0: break (errCode, data) = win32file.ReadFile(x, nAvail, None) self.log_out.write(data)
def read(self) -> str: """ Generator yielding lines read from named pipe. Retry mechanism tries to avoid breaking prematurely while waiting on the other end of the pipe to send data. :return: Lines read from named pipe (str) """ read_buffer = "" max_peek_tries = 3 for stream, frame in frames_iter(socket=self.socket, tty=False): read_buffer += frame.decode("utf8") if read_buffer.endswith("\n"): yield read_buffer.strip("\n") read_buffer = "" peek_tries = 0 while peek_tries <= max_peek_tries: _, n_bytes_left, _ = win32pipe.PeekNamedPipe(self.socket._handle, 2) if n_bytes_left: break else: self.logger.debug("No bytes left to read. Retrying...") self.logger.debug("peek_tries: %s", peek_tries) peek_tries += 1 time.sleep(1) continue else: self.logger.debug("No more bytes left to read") if read_buffer: yield read_buffer.strip("\n") break
def checkWork(self): finished = 0 fullDataRead = [] while 1: try: buffer, bytesToRead, result = win32pipe.PeekNamedPipe(self.pipe, 1) # finished = (result == -1) if not bytesToRead: break hr, data = win32file.ReadFile(self.pipe, bytesToRead, None) fullDataRead.append(data) except win32api.error: finished = 1 break dataBuf = b''.join(fullDataRead) if dataBuf: self.receivedCallback(dataBuf) if finished: self.cleanup() return len(dataBuf)
def pipe_cb(self, *args): """Callback polling for incoming pipe connection and data""" self.poll_id = None nextpoll = self.pipe_poll_ms if self.pipe_status == "waiting": try: self.pipe_status = self.connectq.get(False) except Queue.Empty: pass if self.pipe_status != "connected": self.pipe_schedule(nextpoll) return size = None while size != 0: try: data, size, result = win32pipe.PeekNamedPipe(self.pipe, 1024) except: print("Pipe error, reconnecting") self.pipe_connect() break if size > 0: try: hr, data = win32file.ReadFile(self.pipe, size, None) self.readbuf += data nextpoll = self.pipe_quick_poll_ms except: print("Read failed, reconnecting") self.pipe_connect() size = 0 while len(self.readbuf) >= self.command_len: self.process_command(self.readbuf[:self.command_len]) self.readbuf = self.readbuf[self.command_len:] self.pipe_schedule(nextpoll)
def NonBlockingReadProcessOutput(self, handle): """Does a non-blocking read from the output of the process with the given handle. Args: handle: The process handle returned from os.popen() Returns: A tuple (bytes, output) containing the number of output bytes read, and the actual output. """ output = "" try: osfhandle = msvcrt.get_osfhandle(handle.fileno()) (read, num_avail, num_message) = win32pipe.PeekNamedPipe(osfhandle, 0) if num_avail > 0: (error_code, output) = win32file.ReadFile(osfhandle, num_avail, None) return (num_avail, output) except: return (0, output)
def size(self): """Get the number of bytes available to read on this pipe""" # (lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage) return win32pipe.PeekNamedPipe(self.handle0, 0)[1]
# apri seriale per parlare col programma di gestione # versione named pipe per VirtualBox ser = win32file.CreateFile("\\\\.\\pipe\\planetario", win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) if ser == win32file.INVALID_HANDLE_VALUE: print "can't open named pipe" exit(-1) #ser = serial.Serial(port='COM1', baudrate=4800, timeout=0) # loop di aggiornamento while True: rate(100) # controllori girano a 32.768 ms (circa 30.5 Hz) # verifica che ci siano abbastanza dati nel buffer seriale (buffer, bytesToRead, result) = win32pipe.PeekNamedPipe(ser, 1000) if result and bytesToRead + len(_ser_buffer) >= 5: (result, data) = win32file.ReadFile(ser, bytesToRead) if not result and len(data): if dbg_verbose: for c in data: print "%02X " % (ord(c), ), # appendi nuovi dati da seriale _ser_buffer += data # consuma tutti i dati disponibili isData = True while (isData): (isData, response) = simpla_msg() if isData: if len(response):
(read, nAvail, nMessage) = win32pipe.PeekNamedPipe(x, 0) except pywintypes.error, e: if e.winerror == winerror.ERROR_BROKEN_PIPE: break raise if nAvail > 4096: nAvail = 4096 if nAvail == 0: break (errCode, data) = win32file.ReadFile(x, nAvail, None) self.log_out.write(data) if self.subproc.stderr is not None: while 1: x = msvcrt.get_osfhandle(self.subproc.stderr.fileno()) try: (read, nAvail, nMessage) = win32pipe.PeekNamedPipe(x, 0) except pywintypes.error, e: if e.winerror == winerror.ERROR_BROKEN_PIPE: break raise if nAvail > 4096: nAvail = 4096 if nAvail == 0: break (errCode, data) = win32file.ReadFile(x, nAvail, None) self.log_err.write(data) def tail(self, cnscon, stream, lines=80, tailf=False): if self.state == program_state_enum.CFGERROR: raise svrcall_error("Program {0} is not correctly configured".format(self.ident)) if stream == 'stdout': return self.log_out.tail(cnscon, lines, tailf)