def openPip(_nPip=r'\\.\pipe\Foo', _debugMode=0): if (_debugMode == 1): print("openPip") handle = win32file.CreateFile( _nPip, # filename win32file.GENERIC_READ | win32file. GENERIC_WRITE, # win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, # win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, # win32security.SECURITY_ATTRIBUTES(), win32file.OPEN_EXISTING, # win32con.OPEN_EXISTING, 0, # win32con.FILE_FLAG_OVERLAPPED, None # 0 ) res = win32pipe.SetNamedPipeHandleState( handle, # HANDLE win32pipe. PIPE_READMODE_MESSAGE, # PIPE_READMODE_BYTE OR PIPE_READMODE_MESSAGE None, # PIPE_WAIT OR PIPE_NOWAIT None) # NULL if res == 0: print(f"SetNamedPipeHandleState return code: {res}") return handle
def pipe_client(): try: print("trying to connect to the pipe...") handle = win32file.CreateFile( r'\\.\pipe\my_pipe', win32file.GENERIC_WRITE, #win32file.GENERIC_READ | 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None) win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) # convert to bytes some_data = str.encode( f"English Text:\nThat's life, and as funny as it may seem\n\nGerman Text:\nNicht alles, was zählt, ist zählbar, und nicht alles, was zählbar ist, zählt\n\nRussian Text:\nЖить, как говорится, хорошо! -А хорошо жить - еще лучше! \n\nArmenian Text:\nԾերանալը ձանձրալի է, բայց դա երկար ապրելու միակ միջոցն է:", encoding="utf-8") #f"{count}") overlapped_obj = pywintypes.OVERLAPPED() print("sending the string...") win32file.WriteFile(handle, some_data, overlapped_obj) except pywintypes.error as e: if e.args[0] == 109: print("broken pipe") finally: print("closing handle") handle.Close()
def quit_WeHub_by_pid(wehub_pid): '''优雅地结束掉某一个wehub进程,如果强制kill进程会导致微信崩溃''' process_handle = None pipe_handle = None wehub_pipeName = r'\\.\\pipe\\WeHub' + str(wehub_pid) try: process_handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, wehub_pid) pipe_handle = win32file.CreateFile( wehub_pipeName, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.SetNamedPipeHandleState(pipe_handle, None, None, None) quit_cmd = "q".encode("ascii") if win32file.WriteFile(pipe_handle, quit_cmd): print("quit_cmd have sent") if process_handle: #等待进程退出 print("wait for wehub[%d] terminate..." % wehub_pid) win32event.WaitForSingleObject(process_handle, 5000) print("wehub[%d] exited" % wehub_pid) except Exception as e: raise e finally: if pipe_handle: pipe_handle.Close() if process_handle: process_handle.Close()
def pipe_client(): """ connect to server pipe to send and receive request """ print("pipe client") quit = False print("type q to exit the program") while not quit: try: handle = win32file.CreateFile( r'\\.\pipe\Foo', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None ) res = win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) if res == 0: print(f"SetNamedPipeHandleState return code: {res}") while True: resp = win32file.ReadFile(handle, 64*1024) user_input = input("Tell the Magic 8 Ball your question: ") print(f"message: {resp}") if user_input == "q": sys.exit() except pywintypes.error as e: if e.args[0] == 2: print("no pipe, trying again in a sec") time.sleep(1) elif e.args[0] == 109: print("broken pipe, bye bye") quit = True
def named_pipe_client(): print("Named_Pipe_Client.") # After connected to server for 3 times, it will automatically stop. for cnt in range(3): print(f"Service {cnt+1} is started.") while True: try: # Open the named pipe handle = win32file.CreateFile( r'\\.\pipe\ABC', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) # Set the read or blocking mode of the named pipe res = win32pipe.SetNamedPipeHandleState( handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) if res == 0: print(f"SetNamedPipeHandleState Return Code: {res}" ) # if function fails, the return value will be zero while True: # Read the data from the named Pipe resp = win32file.ReadFile(handle, 65536) print(f"Data Received: {resp}" ) # if function fails, the return value will be zero except pywintypes.error as e: if e.args[0] == 2: # ERROR_FILE_NOT_FOUND print("No Named Pipe") elif e.args[0] == 109: # ERROR_BROKEN_PIPE print("Named Pipe is broken") break print("Service {} is ended.\n".format(cnt + 1)) # Pause for 0.2 second time.sleep(0.2)
def recieve_pipe(): print("pipe client") quit = False while not quit: try: handle = win32file.CreateFile( r'\\.\pipe\Foo', # filename win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) res = win32pipe.SetNamedPipeHandleState( handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) if res == 0: print(f"SetNamedPipeHandleState return code: {res}") while True: resp = win32file.ReadFile(handle, 64 * 1024) print(f"message: {resp}") except pywintypes.error as e: if e.args[0] == 2: print("no pipe, trying again in a sec") time.sleep(1) elif e.args[0] == 109: print("broken pipe, bye bye") quit = True
def conn_loop(self): self.file_handle = win32file.CreateFile( self.ipc_path, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None) if self.file_handle == win32file.INVALID_HANDLE_VALUE: err = win32api.FormatMessage(win32api.GetLastError()) logging.error(f"Failed to connect to pipe: {err}") self.file_handle = None return # needed for blocking on read overlapped = win32file.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) # needed for transactions win32pipe.SetNamedPipeHandleState(self.file_handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) self.is_running = True while self.is_running: val = self._call(win32file.ReadFile, self.file_handle, self._read_buf, overlapped) if not self.is_running: break err, data = val if err != 0 and err != ERROR_IO_PENDING: logger.warning(f"Unexpected read result {err}. Quitting.") logger.debug(f"data={bytes(data)}") self.is_running = False break if err == ERROR_IO_PENDING: err = win32event.WaitForSingleObject(overlapped.hEvent, self.read_timeout) if err == win32event.WAIT_OBJECT_0: # data is available data = bytes(data) line = data[:data.find(b"\n")] self.on_line(line) while not self.write_queue.empty(): # first see if mpv sent some data that needs to be read data = self._call(self._read_all_data) if not self.is_running: break if data: self.on_data(data) # cancel all remaining reads/writes. Should be benign win32file.CancelIo(self.file_handle) write_data = self.write_queue.get_nowait() data = self._call(self._transact, write_data) if not self.is_running: break self.on_line(data[:-1]) self.is_running = False self.file_handle.close() self.file_handle = None logger.debug('Pipe closed.')
def testTransactNamedPipeAsync(self): event = threading.Event() overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) self.startPipeServer(event, 0.5) open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE hpipe = win32file.CreateFile( self.pipename, open_mode, 0, # no sharing None, # default security win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, None, ) # set to message mode. win32pipe.SetNamedPipeHandleState( hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None ) buffer = win32file.AllocateReadBuffer(1024) hr, got = win32pipe.TransactNamedPipe( hpipe, str2bytes("foo\0bar"), buffer, overlapped ) self.assertEqual(hr, winerror.ERROR_IO_PENDING) nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True) got = buffer[:nbytes] self.assertEqual(got, str2bytes("bar\0foo")) event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate")
def open(self, mode='read', pipe_wait=True): wait = win32pipe.PIPE_WAIT if pipe_wait: wait = win32pipe.PIPE_WAIT else: wait = win32pipe.PIPE_NOWAIT create_file = False try: self.__fifo = win32pipe.CreateNamedPipe(rf'\\.\pipe\{self.__pipe}', win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | wait, 1, 65536, 65536, 0, None) print('Waiting for the client to connect') win32pipe.ConnectNamedPipe(self.__fifo, None) print('Client connected') except pywintypes.error as err: if mode == 'read': if err.args[0] == 231: create_file = True else: raise else: raise if mode == 'read' and create_file: self.__fifo = win32file.CreateFile(rf'\\.\pipe\{self.__pipe}', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) result = win32pipe.SetNamedPipeHandleState(self.__fifo, win32pipe.PIPE_READMODE_MESSAGE, None, None) if result == 0: raise Exception('Could not connect to any PIPE') return True
def testTransactNamedPipeBlockingBuffer(self): # Like testTransactNamedPipeBlocking, but a pre-allocated buffer is # passed (not really that useful, but it exercises the code path) event = threading.Event() self.startPipeServer(event) open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE hpipe = win32file.CreateFile( self.pipename, open_mode, 0, # no sharing None, # default security win32con.OPEN_EXISTING, 0, # win32con.FILE_FLAG_OVERLAPPED, None, ) # set to message mode. win32pipe.SetNamedPipeHandleState( hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None ) buffer = win32file.AllocateReadBuffer(1024) hr, got = win32pipe.TransactNamedPipe( hpipe, str2bytes("foo\0bar"), buffer, None ) self.assertEqual(got, str2bytes("bar\0foo")) event.wait(5) self.assertTrue(event.isSet(), "Pipe server thread didn't terminate")
def connect(self, n_attempts=30, delay=1): for i in range(n_attempts): try: self.handle = win32file.CreateFile( r'\\.\pipe\{}'.format(self.name), win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.SetNamedPipeHandleState( self.handle, win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, None, None, ) ActionLogger().log('Connected to the pipe {}'.format( self.name)) break except pywintypes.error as e: if e.args[0] == winerror.ERROR_FILE_NOT_FOUND: ActionLogger().log( 'Attempt {}/{}: failed to connect to the pipe {}'. format(i + 1, n_attempts, self.name)) time.sleep(delay) else: raise BrokenPipeError( 'Unexpected pipe error: {}'.format(e)) if self.handle is not None: return True return False
def start_listen(pipe_name): pipe = win32pipe.CreateNamedPipe( pipe_name, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536, 65536, 0, None) # Waiting for client win32pipe.ConnectNamedPipe(pipe, None) win32pipe.SetNamedPipeHandleState( pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) while True: # Got client try: # Trying to read the message received in the pipe get_command = win32file.ReadFile(pipe, 6) decoded_message = str(get_command[1].decode()) # If the message is *STOP*, we break from the loop if decoded_message == "*STOP*": break except pywintypes.error as e: pass if pipe is not None: win32pipe.DisconnectNamedPipe(pipe) win32pipe.ConnectNamedPipe(pipe, None) win32file.CloseHandle(pipe) return
def _start_socket(self): """Wait for the mpv process to create the unix socket and finish startup. """ # FIXME timeout to give up while self.is_running(): time.sleep(0.1) try: if isWin: self._sock = win32file.CreateFile( r'\\.\pipe\ankimpv', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.SetNamedPipeHandleState( self._sock, 1, # PIPE_NOWAIT None, None) else: self._sock = socket.socket(socket.AF_UNIX) self._sock.connect(self._sock_filename) except (FileNotFoundError, ConnectionRefusedError): continue else: break else: raise MPVProcessError("unable to start process")
def rdt_client(): print("rdt: client begin") count = 0 quit = False while not quit: try: h = win32file.CreateFile( PIPE_RDT, # pipe file name FILE_ACCESS, # desired access mode FILE_SHARE_MODE, # share mode FILE_SECURITY, # security attributes FILE_CREATION, # creation disposition FILE_FLAGS, # flag and attributes FILE_TEMPLATE # template file ) r = win32pipe.SetNamedPipeHandleState( h, # pipe handle PIPE_SET_MODE, # mode PIPE_SET_COLLECTION_MAX_COUNT, # max collection count PIPE_SET_COLLECTION_TIMEOUT # collection data timeout ) if r == 0: e = win32api.GetLastError() print(f"rdt: SetNamedPipeHandleState return code = {e}") while True: #---- task ---- print(f"rdt: send {count}") d = str.encode(f"{count}") # encode to byte stream win32file.WriteFile(h, d) # send time.sleep(1) #---- count += 1 if check_quit(): quit = True break except pywintypes.error as e: if e.args[0] == 2: print("rdt: there is no pipe (try again in a sec)") time.sleep(1) elif e.args[0] == 109: print("rdt: broken pipe") quit = True if check_quit(): quit = True break print("rdt: client end") return
def f连接(self): self.m管道 = win32file.CreateFile( self.m名称, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) v结果 = win32pipe.SetNamedPipeHandleState( self.m管道, win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_NOWAIT, None, None) if v结果 == 0: raise RuntimeError()
def write(self, msg): res = win32pipe.SetNamedPipeHandleState( self.handle, win32pipe.PIPE_READMODE_MESSAGE) if res == 0: print(f"SetNamedPipeHandleState 返回的信息为:{res}") try: _str = tobuff(2018, 2018, msg) win32file.WriteFile(self.handle, _str + bytes(msg)) except Exception as e: print("失败信息为%s" % e)
def set_pipe_mode(hPipe, mode=-1, maxCollectionCount=None, collectDataTimeout=None): # Default values if parameters are not passed if mode == -1: mode = win32pipe.PIPE_READMODE_BYTE try: win32pipe.SetNamedPipeHandleState( hPipe, mode, maxCollectionCount, collectDataTimeout) except pywintypes.error: raise
def __init__(self, name: str): pipe = win32file.CreateFile( '\\\\.\\pipe\\' + name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) if win32pipe.SetNamedPipeHandleState(pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None): raise RuntimeError('Could not set pipe mode to PIPE_TYPE_MESSAGE') root.info('WINAPI: Connected to named pipe %s: %s' % (name, str(pipe))) super(NamedPipeClient, self).__init__(pipe)
def connect(self): '''connect to server pipe''' self.handle = win32file.CreateFile(r'\\.\pipe\%s' % self.pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None ) win32pipe.SetNamedPipeHandleState( self.handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)
def Set_Blocking(self): ''' Set this pipe to blocking access mode. ''' # Only need to change state if nowait is set. if self.nowait_set: self.nowait_set = False win32pipe.SetNamedPipeHandleState( self.pipe_file, win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, None, None) return
def __init__(self, writePipe, lostCallback): self.disconnecting = False self.producer = None self.producerPaused = 0 self.streamingProducer = 0 self.outQueue = [] self.writePipe = writePipe self.lostCallback = lostCallback try: win32pipe.SetNamedPipeHandleState(writePipe, win32pipe.PIPE_NOWAIT, None, None) except pywintypes.error: # Maybe it's an invalid handle. Who knows. pass
def Set_Nonblocking(self): ''' Set this pipe to non-blocking access mode. ''' # Only need to change state if nowait is not already set. # (Use this to reduce overhead for these calls.) if not self.nowait_set: self.nowait_set = True win32pipe.SetNamedPipeHandleState( self.pipe_file, win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_NOWAIT, None, None) return
def foo_client(): print("foo: client begin") quit = False while not quit: try: h = win32file.CreateFile( PIPE_FOO, # pipe file name FILE_ACCESS, # desired access mode FILE_SHARE_MODE, # share mode FILE_SECURITY, # security attributes FILE_CREATION, # creation disposition FILE_FLAGS, # flag and attributes FILE_TEMPLATE # template file ) r = win32pipe.SetNamedPipeHandleState( h, # pipe handle PIPE_SET_MODE, # mode PIPE_SET_COLLECTION_MAX_COUNT, # max collection count PIPE_SET_COLLECTION_TIMEOUT # collection data timeout ) if r == 0: e = win32api.GetLastError() print(f"foo: SetNamedPipeHandleState return code = {e}") while True: #---- task ---- d = win32file.ReadFile( h, PIPE_BUF_SIZE) #---- blocking ---- read byte stream print(f"foo: read {d[1].decode()}") # decide to string #---- if check_quit(): quit = True break except pywintypes.error as e: if e.args[0] == 2: print("foo: there is no pipe (try again in a sec)") time.sleep(1) elif e.args[0] == 109: print("foo: broken pipe") quit = True print("foo: client end") return
def connectPipe(self): if not self.pipe_open: try: self.pipe_handle = win32file.CreateFile(self.pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.SetNamedPipeHandleState(self.pipe_handle, win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, None, None) self.pipe_open = True self.read_msg = None except pywintypes.error as e: self.handleError(e.args[0]) return False return True
def pipe_client(): logging.info('pipe client') quit = False while not quit: try: handle = win32file.CreateFile( # Return Pyhandle object r'\\.\pipe\testpipe', # pipe file name win32file.GENERIC_READ | win32file.GENERIC_WRITE, # desired access 0, # Share mode 0 (once connected, file cannot be shared) None, # SecurityAttributes win32file.OPEN_EXISTING, # Creation Disposition (action to the file if exists/non-exists) 0, # flags and attributes None # Template file ) res = win32pipe.SetNamedPipeHandleState( handle, win32pipe.PIPE_READMODE_MESSAGE, None, None ) if not res: logging.error(f'SetNamePipeHandleState return code: {res}') loop = True while loop: logging.info('Please key in some input:') _ = input() _ = str(_).encode() win32file.WriteFile( handle, _ ) time.sleep(2) hr, msg = win32file.ReadFile( # Return 0 / ERROR_IO_PENDING handle, # fileHandle: obtain from CreateFile() 64*1024) # Integer: number of bytes to be read / ReadBuffer: where the ReadFile operation shoud place the data msg = msg.decode() logging.info(f'message: {msg}') if 'stop' in msg: logging.info('Stop on client') loop = False except pywintypes.error as e: if e.args[0] == 2: logging.warning('no pipe, trying again in a sec') time.sleep(1) elif e.args[0] == 10: logging.error('broken pipe, quit pipe') quit = True
def connect(self): """Connects to the pipe specified in the constructor.""" try: self.handle = win32file.CreateFile( "\\\\.\\pipe\\%s" % (self.name), win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) except pywintypes.error as e: if e.winerror == winerror.ERROR_FILE_NOT_FOUND: raise PipeServerNotFoundError(e.strerror) else: raise e # end except res = win32pipe.SetNamedPipeHandleState( self.handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) if res == 0: raise PipeError("SetNamedPipeHandleState failed.")
def _start_socket(self): """Wait for the mpv process to create the unix socket and finish startup. """ start = time.time() while self.is_running() and time.time() < start + 10: time.sleep(0.1) if isWin: # named pipe try: self._sock = win32file.CreateFile( r"\\.\pipe\ankimpv", win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None, ) win32pipe.SetNamedPipeHandleState( self._sock, 1, None, None # PIPE_NOWAIT ) except pywintypes.error as err: if err.args[0] == winerror.ERROR_FILE_NOT_FOUND: pass else: break else: break else: # unix socket try: self._sock = socket.socket(socket.AF_UNIX) self._sock.connect(self._sock_filename) except (FileNotFoundError, ConnectionRefusedError): self._sock.close() continue else: break else: raise MPVProcessError("unable to start process")
def start_pipe_client(self, conhost, pipename): print("Trying to connect to {}".format(r'\\' + conhost + r'\pipe\\' + pipename)) try: handle = win32file.CreateFile( r'\\' + conhost + r'\pipe\\' + pipename, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) resp = win32file.ReadFile(handle, 1024) except Exception as e: print("Error connecting to client: {}...".format(str(e))) return if resp[1].decode( "utf8", "ignore") == self.__t_myconstant_networking.PIPE_CONNECTED: print("[Client] Connected to", conhost) #have everything normally myuuid = uuid.uuid4().hex[:6].upper() #stager #create fifo self.__mypipe_mydata_list[myuuid] = queue.Queue() #create history self.__mypipe_mymsg_list[myuuid] = list() #push uuid self.__mypipe_myuuid_list.append(myuuid) #set start self.__mypipe_mystart_list[myuuid] = True #pipe name self.__mypipe_mypipename_list[myuuid] = pipename #push pipe handle self.__mypipe_myhandle_list[myuuid] = handle #init psloader self.__mypipe_mypsloader_list[myuuid] = list() print("[Client] myuuid is {}".format(myuuid)) threading.Thread(target=self.start_pipworker, args=(myuuid, )).start() else: print("ACK failed ...")
def c(): me = ' client:' print(f"{me} start") try: handle = win32file.CreateFile( pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, # shareMode None, # PySECURITY_ATTRIBUTES win32file.OPEN_EXISTING, 0, # flagsAndAttributes None) res = win32pipe.SetNamedPipeHandleState( handle, win32pipe.PIPE_READMODE_MESSAGE, None, None) if res == 0: print(f"{me} SetNamedPipeHandleState return code: {res}") time.sleep(1) for i in range(5): command = f'cmd{i}' print(f"{me} write {command}") (err, qty) = win32file.WriteFile(handle, str.encode(command)) assert (err == winerror.S_OK) (err, b) = win32file.ReadFile(handle, pipe_max_msg_size) assert (err == winerror.S_OK) rsp = b.decode() print(f"{me} got: {rsp}") except pywintypes.error as e: if e.args[0] == winerror.ERROR_FILE_NOT_FOUND: print(me, e.args[0], e) elif e.args[0] == winerror.ERROR_BROKEN_PIPE: print(me, 'pipe closed', e) except Exception as e: print(me, e) try: win32file.CloseHandle(handle) except Exception as e: print(me, 'Closed handle', e) print(f"{me} done")
def SCTDCStart(self, acqtime): BUFFSIZE = 1024 * 1024 target_buffer = POINTER(c_char * BUFFSIZE)() target_buffer.contents = (c_char * BUFFSIZE)() read_buffer = POINTER(c_char * BUFFSIZE)() read_buffer.contents = (c_char * BUFFSIZE)() mybuffer = win32file.AllocateReadBuffer(1024 * 1024) win32pipe.SetNamedPipeHandleState(self.hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) success = win32pipe.TransactNamedPipe( self.hpipe, str2bytes("START %i" % (acqtime)), mybuffer, None) #↨win32pipe.DisconnectNamedPipe(self.hpipe) #win32file.CloseHandle(self.hpipe) return success