def send(self,raw_data,retry_timeout=1): """ Writes raw outgoing data. Blocks until done. If supplied data is unicode string, encodes it to utf-8 before send.""" if type(raw_data)==type(u''): raw_data = raw_data.encode('utf-8') elif type(raw_data)<>type(''): raw_data = ustr(raw_data).encode('utf-8') try: sent = 0 while not sent: try: self._send(raw_data) sent = 1 except socket.sslerror, e: if e[0]==socket.SSL_ERROR_WANT_READ: sys.exc_clear() self.DEBUG("SSL_WANT_READ while sending data, wating to retry",'warn') select.select([self._sock],[],[],retry_timeout) continue if e[0]==socket.SSL_ERROR_WANT_WRITE: sys.exc_clear() self.DEBUG("SSL_WANT_WRITE while sending data, waiting to retry",'warn') select.select([],[self._sock],[],retry_timeout) continue raise # Avoid printing messages that are empty keepalive packets. if raw_data.strip(): self.DEBUG(raw_data,'sent') if hasattr(self._owner, 'Dispatcher'): # HTTPPROXYsocket will send data before we have a Dispatcher self._owner.Dispatcher.Event('', DATA_SENT, raw_data)
def run(self): self.client_conn.setblocking(1) file_stat=os.stat(self.file_name)[6] #file_stat_s=file_stat[0:len(file_stat)-1] file_stat_s=str(file_stat) infds,outfds,errfds=select.select([],[self.client_sock_fd],[],int(self.global_config_hash['CONNECT_TIMEOUT'])) if(len(outfds)==0): GeneralOperationThread.unversal_write_log_2(self.log_fd,"Step1 check failed write to client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" try: self.client_conn.send(file_stat_s + "\r\n") except: print "Error to send file size to client" GeneralOperationThread.unversal_write_log_2(self.log_fd,"Error to send file size to client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" try: recv_len=None infds,outfds,errfds=select.select([self.client_sock_fd],[],[],int(self.global_config_hash['CONNECT_TIMEOUT'])) if(len(infds) !=0): recv_len=self.client_conn.recv(1024) if(recv_len is None or recv_len.strip() != "ok" or len(recv_len)>=1023 or len(recv_len)<=0): #self.epoll_fd.unregister(self.client_sock_fd) GeneralOperationThread.unversal_write_log_2(self.log_fd,"Error to recv file size ok from client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" except: GeneralOperationThread.unversal_write_log_2(self.log_fd,"Except to recv file size ok from client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" infds,outfds,errfds=select.select([],[self.client_sock_fd],[],int(self.global_config_hash['CONNECT_TIMEOUT'])) if(len(outfds)==0): GeneralOperationThread.unversal_write_log_2(self.log_fd,"Check write failed from client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" try: file_read_handle=open(self.file_name,"rb") except: GeneralOperationThread.unversal_write_log_2(self.log_fd,"Open file failed from client" + self.file_name + self.file_user + "\n") self.client_conn.close() return "Error" try: file_read_tmp=file_read_handle.read(4096) while file_read_tmp: self.client_conn.send(file_read_tmp) file_read_tmp=file_read_handle.read(4096) except: GeneralOperationThread.unversal_write_log_2(self.log_fd,"Error to read file for binary mode" + self.file_name + self.file_user + "\n") print "File binary read error" finally: file_read_handle.close() #here useful for new version #try: # last_tok=self.client_conn.recv(1024) #except: # pass self.client_conn.close() GeneralOperationThread.unversal_write_log_2(self.log_fd,"Done to send file for binary mode" + self.file_name + self.file_user + "\n") return "ok"
def wait_select(conn): """Wait until a connection or cursor has data available. The function is an example of a wait callback to be registered with `~psycopg2.extensions.set_wait_callback()`. This function uses :py:func:`~select.select()` to wait for data available. """ import select from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE while 1: try: state = conn.poll() if state == POLL_OK: break elif state == POLL_READ: select.select([conn.fileno()], [], []) elif state == POLL_WRITE: select.select([], [conn.fileno()], []) else: raise conn.OperationalError("bad state from poll: %s" % state) except KeyboardInterrupt: conn.cancel() # the loop will be broken by a server error continue
def sendMsg(self,outData, maxretry = 5, interval = 1): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # s.bind((self.host, self.port+1)) # make sure buffer empty while select([s],[],[], 0)[0]: (inData,addy) = s.recvfrom(1024) s.sendto(outData, (self.host, self.port)) time.sleep(.1) #s.sendto(outData, (self.host, self.port)) string = "" while string == "" and maxretry > 0: maxretry -= 1 # on last attempt resend the message ? need to protect against json errors #if maxretry == 0: # interval *= 3 # s.sendto(outData, (self.host, self.port)) time.sleep(interval) while select([s],[],[], 0)[0]: (inData,addy) = s.recvfrom(2048) string = string + inData #if string == "": # return "" #return "["+string.split('][')[-1].strip('[]')+']' return string
def _connect(self, attempts=0): if attempts > 500: msg.error('Connection attempt timed out.') return self.reconnect() if not self.sock: msg.debug('_connect: No socket') return try: self.sock.connect((self.host, self.port)) select.select([self.sock], [self.sock], [], 0) except socket.error as e: if e.errno == iscon_errno: pass elif e.errno in connect_errno: return utils.set_timeout(self._connect, 20, attempts + 1) else: msg.error('Error connecting:', e) return self.reconnect() if self.secure: sock_debug('SSL-wrapping socket') self.sock = ssl.wrap_socket(self.sock, ca_certs=self.cert_path, cert_reqs=ssl.CERT_REQUIRED, do_handshake_on_connect=False) self.on_connect() self.call_select = True self.select()
def process(self): """Entry point of SelectableSelector""" if WINDOWS: select_inputs = [] for i in self.inputs: if not isinstance(i, SelectableObject): warning("Unknown ignored object type: %s", type(i)) elif i.__selectable_force_select__: # Then use select.select select_inputs.append(i) elif not self.remain and i.check_recv(): self.results.append(i) else: i.wait_return(self._exit_door) if select_inputs: # Use default select function self.results.extend(select(select_inputs, [], [], self.remain)[0]) # noqa: E501 if not self.remain: return self.results threading.Thread(target=self._timeout_thread, args=(self.remain,)).start() # noqa: E501 if not self._ended: self.available_lock.acquire() return self.results else: r, _, _ = select(self.inputs, [], [], self.remain) return r
def processInput(self): """Wait for and process a single packet.""" pkt = Packet() select.select([self._sock], [], []) pkt.read(self._sock) # Body chunks have no packet type code. if self._request is not None: self._processBody(pkt) return if not pkt.length: raise ProtocolError('unexpected empty packet') pkttype = pkt.data[0] if pkttype == PKTTYPE_FWD_REQ: self._forwardRequest(pkt) elif pkttype == PKTTYPE_SHUTDOWN: self._shutdown(pkt) elif pkttype == PKTTYPE_PING: self._ping(pkt) elif pkttype == PKTTYPE_CPING: self._cping(pkt) else: raise ProtocolError('unknown packet type')
def wrap(socket_obj, ssl_connection, fun, *params): ''' A utility function that calls SSL read/write operation and handles errors. ''' while True: try: result = fun(*params) break except SSL.WantReadError: select.select([socket_obj], [], [], 3) except SSL.WantWriteError: select.select([], [socket_obj], [], 3) except SSL.ZeroReturnError: # The remote end closed the connection ssl_connection.shutdown() raise SSL.ZeroReturnError except SSL.Error, ssl_error: # This is raised when the browser abruptly closes the # connection, in order to show the user the "false" w3af MITM certificate # and ask if he/she trusts it. # Error: [('SSL routines', 'SSL3_READ_BYTES', 'ssl handshake failure')] try: msg = ssl_error[0][0][2] except Exception: # Not an error of the type that I was expecting! raise ssl_error else: if msg == 'ssl handshake failure': msg = 'Asking the user about the invalid w3af MITM certificate.' \ ' He must accept it.' om.out.debug(msg) ssl_connection.shutdown() raise ssl_error else: raise ssl_error
def _select(self, readers=None, writers=None, err=None, timeout=0): readers = set() if readers is None else readers writers = set() if writers is None else writers err = set() if err is None else err try: r, w, e = select.select(readers, writers, err, timeout) if e: seen = set() r = r | set(f for f in r + e if f not in seen and not seen.add(f)) return r, w, 0 except (select.error, socket.error) as exc: if get_errno(exc) == errno.EINTR: return [], [], 1 elif get_errno(exc) in SELECT_BAD_FD: for fd in readers | writers | err: try: select.select([fd], [], [], 0) except (select.error, socket.error) as exc: if get_errno(exc) not in SELECT_BAD_FD: raise readers.discard(fd) writers.discard(fd) err.discard(fd) return [], [], 1 else: raise
def __iowait(self, io_func, *args, **kwargs): timeout = self._sock.gettimeout() or 0.1 fd = self._sock.fileno() time_start = time.time() while True: try: return io_func(*args, **kwargs) except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError): sys.exc_clear() _, _, errors = select.select([fd], [], [fd], timeout) if errors: raise time_now = time.time() if time_now - time_start > timeout: break except OpenSSL.SSL.WantWriteError: sys.exc_clear() _, _, errors = select.select([], [fd], [fd], timeout) if errors: raise time_now = time.time() if time_now - time_start > timeout: break except Exception as e: #xlog.exception("e:%r", e) raise e
def handle_until_return(self): child_stdin = self.popen.stdin child_stdout = self.popen.stdout if self.os_level_sandboxing and sys.platform.startswith('linux2'): # rationale: we wait until the child process started completely, # letting the C library do any system calls it wants for # initialization. When the RPython code starts up, it quickly # does its first system call. At this point we turn seccomp on. import select select.select([child_stdout], [], []) f = open('/proc/%d/seccomp' % self.popen.pid, 'w') print >> f, 1 f.close() while True: try: fnname = read_message(child_stdout) args = read_message(child_stdout) except EOFError, e: break if self.debug and not self.is_spam(fnname, *args): log.call('%s(%s)' % (fnname, ', '.join([shortrepr(x) for x in args]))) try: answer, resulttype = self.handle_message(fnname, *args) except Exception, e: tb = sys.exc_info()[2] write_exception(child_stdin, e, tb) if self.debug: if str(e): log.exception('%s: %s' % (e.__class__.__name__, e)) else: log.exception('%s' % (e.__class__.__name__,))
def poll(): """Poll the select """ recv = send = [] try: if os.name != 'posix': if IOHandlers()._handler_pool: recv, send, _ = select.select( IOHandlers().ready_to_read(), IOHandlers().ready_to_write(), [], 0 ) else: recv, send, _ = select.select( IOHandlers().ready_to_read(), IOHandlers().ready_to_write(), [], 0 ) except select.error: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: return raise for handler in recv: if handler is None or handler.ready_to_read() is not True: continue handler.recv() for handler in send: if handler is None or handler.ready_to_write() is not True: continue handler.send()
def write(self, data): """Output the given string over the serial port.""" if self.sock is None: raise serial.portNotOpenError t = len(data) d = data while t > 0: try: if self._writeTimeout is not None and self._writeTimeout > 0: _,ready,_ = select.select([],[self.sock],[], self._writeTimeout) if not ready: raise serial.writeTimeoutError n = self.sock.send(d) if self._dump: print hexdump(d[:n]) if self._writeTimeout is not None and self._writeTimeout > 0: _,ready,_ = select.select([],[self.sock],[], self._writeTimeout) if not ready: raise serial.writeTimeoutError d = d[n:] t = t - n except OSError,v: if v.errno != errno.EAGAIN: raise
def receive(sdef, slen=SLEN): sdef.setblocking(1) ready = select.select([sdef], [], [sdef], LTIMEOUT) if ready[0]: try: data = int(sdef.recv(slen)) # receive length #print ("To receive: {}".format(data)) except: raise RuntimeError("Connection closed by the remote host") #do away with the invalid literal for int else: # logical timeout return "*" #raise RuntimeError("Socket timeout") chunks = [] bytes_recd = 0 while bytes_recd < data: ready = select.select([sdef], [], [], LTIMEOUT) if ready[0]: chunk = sdef.recv(min(data - bytes_recd, 2048)) if not chunk: raise RuntimeError("Socket connection broken") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) else: raise RuntimeError("Socket timeout") segments = b''.join(chunks).decode("utf-8") #print("Received segments: {}".format(segments)) return json.loads(segments)
def getCommandOutput2(command): child = popen2.Popen3(command, 1) # Capture stdout and stderr from command child.tochild.close( ) # don't need to write to child's stdin outfile = child.fromchild outfd = outfile.fileno( ) errfile = child.childerr errfd = errfile.fileno( ) makeNonBlocking(outfd) # Don't deadlock! Make fd's nonblocking. makeNonBlocking(errfd) outdata, errdata = [ ], [ ] outeof = erreof = False while True: to_check = [outfd]*(not outeof) + [errfd]*(not erreof) ready = select.select(to_check, [ ], [ ]) # Wait for input if outfd in ready[0]: outchunk = outfile.read( ) if outchunk == '': outeof = True else: outdata.append(outchunk) if errfd in ready[0]: errchunk = errfile.read( ) if errchunk == '': erreof = True else: errdata.append(errchunk) if outeof and erreof: break select.select([ ],[ ],[ ],.1) # Allow a little time for buffers to fill err = child.wait( ) if err != 0: raise RuntimeError, '%r failed with exit code %d\n%s' % ( command, err, ''.join(errdata)) return ''.join(outdata)
def run(self): ''' Start the loop; use select.select to watch the handle for input and output; runs ccn_run if there is input/output or select timeout ''' self.running = True # select.poll() is disabled in Mac OS X.. dafaq?! #poller = select.poll() #poller.register(self.handle.fileno(), select.POLLIN | select.POLLOUT) inputs = [self.handle] while (self.running): self.handle.run(0) outputs = [] if self.handle.output_is_pending(): outputs.append(self.handle) # time out is in seconds try: select.select(inputs, outputs, [], 0.05) except TypeError: # sometimes when use Ctrl-C to kill the process # it would have TypeError: an integer is required # have no idea what is the problem yet # but since we are shutting down, so probably it's ok # to ignore this problem pass
def run(self): rd, wr, err = select(self.sockets, [], self.sockets, 0) # Accept new connections if self.server in rd: self.accept() rd.remove(self.server) # Read from sockets for sock in rd: self.socket_receive(sock) # Write buffers to sockets rd, wr, err = select([], self.clients, [], 0) for client in wr: try: buff = self.clients_sendbuffer[client] if len(buff) > 0: sent = client.send(buff) self.clients_sendbuffer[client] = buff[sent:] except: self.close(client) # Drop starving clients for client in self.clients: if len(self.clients_sendbuffer[client]) > 8192: self.close(client)
def write(self, data): """Output the given string over the serial port.""" if not self._isOpen: raise portNotOpenError d = to_bytes(data) tx_len = len(d) if self._writeTimeout is not None and self._writeTimeout > 0: timeout = time.time() + self._writeTimeout else: timeout = None while tx_len > 0: try: n = os.write(self.fd, d) if timeout: # when timeout is set, use select to wait for being ready # with the time left as timeout timeleft = timeout - time.time() if timeleft < 0: raise writeTimeoutError _, ready, _ = select.select([], [self.fd], [], timeleft) if not ready: raise writeTimeoutError else: # wait for write operation _, ready, _ = select.select([], [self.fd], [], None) if not ready: raise SerialException('write failed (select)') d = d[n:] tx_len -= n except OSError, v: if v.errno != errno.EAGAIN: raise SerialException('write failed: %s' % (v,))
def _drain(fd, timeout=0.3): more, _, _ = select.select([fd], [], [], timeout) buf = b'' while more: buf += os.read(fd, 1024) more, _, _ = select.select([fd], [], [], timeout) return buf
def _connect(self, host, port, attempts=0): if attempts > (self.proxy and 500 or 500): msg.error('Connection attempt timed out.') return self.reconnect() if not self._sock: msg.debug('_connect: No socket') return try: self._sock.connect((host, port)) select.select([self._sock], [self._sock], [], 0) except socket.error as e: if e.errno == iscon_errno: pass elif e.errno in connect_errno: msg.debug('connect_errno: ', str_e(e)) return utils.set_timeout(self._connect, 20, host, port, attempts + 1) else: msg.error('Error connecting: ', str_e(e)) return self.reconnect() if self._secure: sock_debug('SSL-wrapping socket') self._sock = ssl.wrap_socket(self._sock, ca_certs=self._cert_path, cert_reqs=ssl.CERT_REQUIRED, do_handshake_on_connect=False) self._q.clear() self._buf_out = bytes() self.emit('connect') self.connected = True
def iteration(self): """ A single context iteration """ fds = self._watch_files.keys() if self._alarms or self._did_something: if self._alarms: tm = self._alarms[0][0] timeout = max(0, tm-time.time()) if self._did_something and (not self._alarms or timeout > 0): timeout = 0 tm = 'idle' ready, w, err = select.select(fds, [], fds, timeout) else: tm = None ready, w, err = select.select(fds, [], fds) if not ready: if tm == 'idle': self._did_something = False self._dispatch_idle() elif tm is not None: # must gave been a timeout tm, alarm_callback = self._alarms.pop(0) alarm_callback() self._did_something = True for fd in ready: self._watch_files[fd]() self._did_something = True
def run(self): self.remote.connect(self.remote_addr) self.remote.setblocking(1) while not self.please_die: ready_to_read, ready_to_write, in_error = select([self.local], [], [], 0.1) if len(ready_to_read) > 0: try: msg = self.local.recv(1024) except Exception as err: print("ERRO: " + str(self.getName()) + " > " + str(err)) break else: magiaremote = msg.replace(mycfg['clt2srv.msgoriginal'], mycfg['clt2srv.msgalterada'], 1) self.remote.send(magiaremote) # ver se o servidor tem algo a dizer ready_to_read, ready_to_write, in_error = select([self.remote], [], [], 0.1) if len(ready_to_read) > 0: try: msg = self.remote.recv(1024) except Exception as err: print("ERRO: " + str(self.getName()) + " > " + str(err)) break else: magia = msg.replace(mycfg['srv2clt.msgoriginal'],mycfg['srv2clt.msgalterada'], 1) if magia != "": #print("<< {0}".format(repr(msg))) self.local.send(magia) else: break self.remote.close() self.local.close() self.server.accepted.pop(self.getName())
def wait_child(self): """Wait for child progress to exit. This method is responsible for calling update_interface() from time to time. It exits once the child has exited. The return values is the full status returned from os.waitpid() (not only the return code). """ (pid, res) = (0, 0) while True: try: select.select([self.status_stream], [], [], self.select_timeout) except select.error as (errno_, _errstr): if errno_ != errno.EINTR: raise self.update_interface() try: (pid, res) = os.waitpid(self.child_pid, os.WNOHANG) if pid == self.child_pid: break except OSError as err: if err.errno == errno.ECHILD: break if err.errno != errno.EINTR: raise
def test_select1(self): import select import socket s1, s2 = socket.socketpair() with hub.Timeout(1, MyException): select.select([s2.fileno()], [], [])
def shell_call(cmd): # subprocess.call(cmd) ON_POSIX = 'posix' in sys.builtin_module_names hpipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, close_fds=ON_POSIX, shell=True) # Change to non-blocking mode, so read returns even if there is no data. fcntl.fcntl(hpipe.stdout, fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(hpipe.stderr, fcntl.F_SETFL, os.O_NONBLOCK) total_output_stdout = '' total_output_stderr = '' while True: # wait for data to become available select.select([hpipe.stdout, hpipe.stderr], [], []) # Try reading some data from each output_stdout = read_async(hpipe.stdout) output_stderr = read_async(hpipe.stderr) if output_stdout: stdout_write(output_stdout) total_output_stdout += output_stdout if output_stderr: stdout_write(output_stderr) total_output_stderr += output_stderr rc = hpipe.poll() if rc != None: return total_output_stdout + total_output_stderr
def forward_data(self): log.warn(messages.module_backdoor_reversetcp.reverse_shell_connected) self.socket.setblocking(0) while(1): read_ready, write_ready, in_error = select.select( [self.socket, sys.stdin], [], [self.socket, sys.stdin]) try: buffer = self.socket.recv(100) while(buffer != ''): self.socket_state = True sys.stdout.write(buffer) sys.stdout.flush() buffer = self.socket.recv(100) if(buffer == ''): return except socket.error: pass while(1): r, w, e = select.select([sys.stdin], [], [], 0) if(len(r) == 0): break c = sys.stdin.read(1) if(c == ''): return if(self.socket.sendall(c) != None): return
def handle_write(self): "The connection is ready for writing; write any buffered data." try: # This write could be more efficient and coalesce multiple elements # of the _write_buffer into a single write. However, the stock # ssl library with python needs us to pass the same buffer back # after a socket.send() returns 0 bytes. To fix this, we need # to use the SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this can # only be done on the context in the ssl.c code. So, we work # around this problem by not coalescing buffers. Repeated calls # to handle_write after SSL errors always hand the same buffer # to the SSL library, and it works. while len(self._write_buffer): data = self._write_buffer[0] sent = self.socket.send(self._write_buffer[0]) if sent == len(self._write_buffer[0]): self._write_buffer = self._write_buffer[1:] else: # Only did a partial write. self._write_buffer[0] = self._write_buffer[0][sent:] except ssl.SSLError, err: logging.error(str(self.socket) + "SSL Write error: " + str(err)) if err.args[0] == ssl.SSL_ERROR_WANT_READ: select.select([self.socket], [], []) elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: select.select([], [self.socket], []) else: raise
def __init__(self, host, port, encoding='utf8', use_ssl=False): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) # We need non-blocking so it won't hang when there is no data. self.socket.setblocking(False) if use_ssl: self.socket = ssl.wrap_socket( self.socket, do_handshake_on_connect=False) # We need to do the handshake manually, because we use a # non-blocking socket. # https://docs.python.org/2/library/ssl.html#ssl-nonblocking while True: try: self.socket.do_handshake() break except ssl.SSLWantReadError: select.select([self.socket], [], []) except ssl.SSLWantWriteError: select.select([], [self.socket], []) self.encoding = encoding self.buffer = LineBuffer(self.encoding) self.me = User('')
def getKey(): '''get key press (from example code)''' tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) key = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) return key
def run(self): fromshell,toshell,fromfd,tofd =\ self.fromshell,self.toshell,self.fromfd,self.tofd while not fromshell.closed and not toshell.closed: # only interested in fd's which we can currently read from readables = select([fromshell, fromfd],[],[])[0] for r in readables: if r == fromshell: # read now, because next statement might block for a while data = r.read() # hackish way to wait until socket becomes ready # had errors when just trying to naively writing to socket # select blocks until 'tofd' is ready for writing # returns [[],[tofd],[]], which is unpacked by # subscripts select([],[tofd],[])[1][0].write(data) # this IS important tofd.flush() elif r == fromfd: # analogous to above data = r.read() select([],[toshell],[])[1][0].write(data) toshell.flush() else: raise Exception("please slap the programmer")
def clear(self): rlist, wlist, xlist = select.select([self._socket], [], [], 0) if len(rlist) == 0: return ret = self.read()
def _poll(self, timeout=0.1): if self._is_source(): raise IOError('No input pipe for this ability instance: {}'.format( type(self).get_name())) r, w, x = select.select(self._builtin_in_pipes, [], [], timeout) return len(r) > 0
sockets_list = [server_socket] clients = {} def receive_message(client_socket): try: message_header = client_socket.recv(HEADER_LENGTH) if not len(message_header): return False message_length = int(message_header.decode("utf-8").strip()) return {"header": message_header, "data": client_socket.recv(message_length)} except: #the only way to reach this is if someone somehow broke their script return False while True: read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list) #select.select takes in 3 parameters, the things you want to read, sockets you want to write, and sockets you want to air on for notified_socket in read_sockets: if notified_socket == server_socket: client_socket, client_address = server_socket.accept() user = receive_message(client_socket) if user is False: continue sockets_list.append(client_socket) clients[client_socket] = user print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user['data'].decode('utf-8')}") else: message = receive_message(notified_socket)
def updateBlocking(self, timeout=1.0): rlist, _, _ = select([self.ser], [], [], timeout) if rlist: self.update()
import socket import pickle import select server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("0.0.0.0", 8082)) server.listen(1) inputs = [server] try: while True: readable, _, _ = select.select(inputs, [], []) for s in readable: if s is server: conn, addr = server.accept() inputs.append(conn) else: data = s.recv(4096) if data: data = pickle.loads(data) s.sendall( pickle.dumps(eval(f"{data[0]}{data[2]}{data[1]}"))) else: s.close() inputs.remove(s) finally: server.close()
def serveforever(self): while True: writers = [] for fileno in self.listeners: if fileno == self.serversocket: continue client = self.connections[fileno] if client.sendq: writers.append(fileno) if self.selectInterval: rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval) else: rList, wList, xList = select(self.listeners, writers, self.listeners) for ready in wList: client = self.connections[ready] try: while client.sendq: opcode, payload = client.sendq.popleft() remaining = client._sendBuffer(payload) if remaining is not None: client.sendq.appendleft((opcode, remaining)) break else: if opcode == CLOSE: raise Exception('received client close') except Exception: client.client.close() client.handleClose() del self.connections[ready] self.listeners.remove(ready) for ready in rList: if ready == self.serversocket: try: sock, address = self.serversocket.accept() newsock = self._decorateSocket(sock) newsock.setblocking(0) fileno = newsock.fileno() self.connections[fileno] = self._constructWebSocket( newsock, address) self.listeners.append(fileno) except Exception: if sock is not None: sock.close() else: if ready not in self.connections: continue client = self.connections[ready] try: client._handleData() except Exception: client.client.close() client.handleClose() del self.connections[ready] self.listeners.remove(ready) for failed in xList: if failed == self.serversocket: self.close() raise Exception('server socket failed') else: if failed not in self.connections: continue client = self.connections[failed] client.client.close() client.handleClose() del self.connections[failed] self.listeners.remove(failed)
""" select 方法示例 """ from select import select from socket import * f = open('test.log') sockfd = socket() sockfd.bind(('0.0.0.0', 8888)) sockfd.listen(5) udp = socket(AF_INET, SOCK_DGRAM) udp.bind(('0.0.0.0', 9999)) print('开始监控IO') rs, ws, xs = select([udp], [], []) print('rlist:', rs) print('wlist:', ws) print('xlist:', xs)
def recv_ready(self): s = self.sock return select.select([s], [], [], WTIME) == ([s], [], [])
sys.exit(-1) # Get any initial tab (functions, colors, etc) # Just look at the first letter initial_tab = '' if len(sys.argv) > 1: for tab in ['functions', 'prompt', 'colors', 'variables', 'history', 'bindings']: if tab.startswith(sys.argv[1]): initial_tab = '#' + tab break url = 'http://localhost:%d/%s' % (PORT, initial_tab) print("Web config started at '%s'. Hit enter to stop." % url) webbrowser.open(url) # Select on stdin and httpd stdin_no = sys.stdin.fileno() try: while True: ready_read = select.select([sys.stdin.fileno(), httpd.fileno()], [], []) if ready_read[0][0] < 1: print("Shutting down.") # Consume the newline so it doesn't get printed by the caller sys.stdin.readline() break else: httpd.handle_request() except KeyboardInterrupt: print("\nShutting down.")
def read_all(self, tn, rbytes=RBYTES, waittime=WTIME): t = "" while select.select([tn], [], [], WTIME) == ([tn], [], []): t += tn.recv(rbytes) return t
my_classifier.eval() transform = preprocess.make_transform(mode="predict") plt.ion() camera_url = "http://*****:*****@ip:8080/photo.jpg" while True: r = requests.get(camera_url) f = io.BytesIO(r.content) im = imread(f) im = rotate(im, -90, resize=True) im = im[420:-420, :] im = transform(np.float32(im)) im = im.view(1, 3, 224, 224) show_im = np.clip(im[0].numpy().transpose(1, 2, 0), 0, 1) plt.clf() plt.imshow(show_im) plt.draw() plt.pause(0.01) with torch.no_grad(): pred = my_classifier(im.to(device)) pred = torch.argmax(pred, axis=1).cpu().item() print(pred, labels[pred]) inp, o, e = select.select([sys.stdin], [], [], 1) if inp: if sys.stdin.readline().strip() == "q": plt.close() break
def send_ready(self): s = self.sock return select.select([], [s], [], WTIME) == ([], [s], [])
def run_devourer(self, LFIp, LFPort): self.active_socket = self.create_udp_send_chanel() self.active_socket.setblocking(False) single_socket_list = [ self.active_socket, ] self.session_sequence_number += 1 protocol_data = ProtocolPilot.create_sync_info(self) data_message = ProtocolPilot.generate_protocol_message( protocol_data, PROTOCOL_DCCP_SYNC) self.active_socket.sendto(binascii.a2b_hex(data_message), (LFIp, LFPort)) while True: readable_list, writeable_list, error_list = select.select( single_socket_list, [], single_socket_list, 1) for r in readable_list: received = r.recv(2048) if received: data_obj = ProtocolPilot.parse_dccp_packet(received)[0] if data_obj is None: continue if data_obj.protocol_type == PROTOCOL_HEAD_DCCP: if data_obj.protocol_sub_type == PROTOCOL_DCCP_SYNC: pass if data_obj.protocol_sub_type == PROTOCOL_DCCP_SYNACK: self.session_ack_number = data_obj.protocol_seqno tmp_req = ProtocolPilot.create_protocol_struct( self, PROTOCOL_CCCP_PUSH_STREAM_REQ, None, None, opt=1) tmp_data = ProtocolPilot.create_protocol_struct( self, PROTOCOL_DCCP_DATA, None, tmp_req) self.session_sequence_number += 1 req_data = ProtocolPilot.create_protocol_struct( self, PROTOCOL_HEAD_DCCP, PROTOCOL_DCCP_DATA, tmp_data, iack=1) req_message = ProtocolPilot.generate_protocol_message( req_data, PROTOCOL_DCCP_DATA) self.active_socket.sendto( binascii.a2b_hex(req_message), (LFIp, LFPort)) if data_obj.protocol_sub_type == PROTOCOL_DCCP_DATA: if data_obj.protocol_data.protocol_type == PROTOCOL_CCCP_PUSH_STREAM_REQ: pass if data_obj.protocol_data.protocol_type == PROTOCOL_CCCP_PUSH_STREAM_RSP: if data_obj.protocol_iack == 1: self.session_ack_number = data_obj.protocol_seqno self.session_sequence_number += 1 ack_data = ProtocolPilot.create_ack_info( self, 1) ack_message = ProtocolPilot.generate_protocol_message( ack_data, PROTOCOL_DCCP_ACK) self.active_socket.sendto( binascii.a2b_hex(ack_message), (LFIp, LFPort)) # status == 5 sdk is busy if data_obj.protocol_data.protocol_data.status == 5: time.sleep(1) self.session_sequence_number += 1 protocol_data = ProtocolPilot.create_sync_info( self) data_message = ProtocolPilot.generate_protocol_message( protocol_data, PROTOCOL_DCCP_SYNC) self.active_socket.sendto( binascii.a2b_hex(data_message), (LFIp, LFPort)) if data_obj.protocol_data.protocol_type == PROTOCOL_CCCP_PUSH_PIECE_DATA: self.session_ack_number = data_obj.protocol_seqno if data_obj.protocol_data.protocol_type == PROTOCOL_CCCP_PUSH_STREAM_FIN: self.session_ack_number = data_obj.protocol_seqno if data_obj.protocol_sub_type == PROTOCOL_DCCP_ACK: if data_obj.protocol_iack == 1: self.session_ack_number = data_obj.protocol_seqno self.session_sequence_number += 1 ack_data = ProtocolPilot.create_ack_info( self, 1) ack_message = ProtocolPilot.generate_protocol_message( ack_data, PROTOCOL_DCCP_ACK) self.active_socket.sendto( binascii.a2b_hex(ack_message), (LFIp, LFPort)) self.clean_ack_timer() if data_obj.protocol_sub_type == PROTOCOL_DCCP_FIN: pass if self.ack_timer_check(): ack_data = ProtocolPilot.create_ack_info(self) ack_message = ProtocolPilot.generate_protocol_message( ack_data, PROTOCOL_DCCP_ACK) self.active_socket.sendto(binascii.a2b_hex(ack_message), (LFIp, LFPort))
# Send greeting to server try: s.sendto('GREETING', (host, port)) except: print 'Unable to connect to server' sys.exit() print 'Connected to server. Start sending messages' # Show the prompt to the user so that he can start sending messages. prompt() while 1: socket_list = [sys.stdin, s] # Get all sockects for the client # Get the list sockets which are readable read_sockets, write_sockets, error_sockets = select.select( socket_list, [], []) for sock in read_sockets: #incoming message from server if sock == s: data = sock.recvfrom(RECV_BUFFER) if not data: print '\nDisconnected from chat server' sys.exit() else: # print the incoming data(message) and display the prompt again sys.stdout.write(data[0]) prompt() #user typed a message and is sending it accross else:
self.traj_points = list( np.concatenate(([x_fine], [y_fine], [z_fine]), axis=0).T) if __name__ == '__main__': smooth_ar_tracker = SmoothAR() rate = rospy.Rate(5) try: while not rospy.is_shutdown(): if (smooth_ar_tracker.flag1 == 0 ): # If we are in AR tag data collection mode while True: os.system('cls' if os.name == 'nt' else 'clear') smooth_ar_tracker.ar_track(0.3) rate.sleep() if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: line = raw_input() print('Stopping tracking') smooth_ar_tracker.flag1 = 1 break #arr_temp= np.array(smooth_ar_tracker.camera_pose_list) #np.save('/home/ashish/Desktop/phantom_vision_ws/src/phantom_vision_project/traj_follower/scripts/bag1.npy', arr_temp) #temp= np.load('/home/ashish/Desktop/phantom_vision_ws/src/phantom_vision_project/traj_follower/scripts/bag1.npy') #print (temp) #smooth_ar_tracker.camera_pose_list= list(temp) smooth_ar_tracker.transform_world() smooth_ar_tracker.getPolyTrajectory() smooth_ar_tracker.visualize_pose_world() smooth_ar_tracker.visualize_pose_camera() smooth_ar_tracker.visualize_traj() if (smooth_ar_tracker.flag2 == 0):
f = open('priv.pem','r') key = RSA.importKey(f.read()) c1_flag = pow(int("0x"+(binascii.b2a_hex(flag.encode())).decode(), 16), key.e, key.n) soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.bind((hote, port)) soc.listen(64) print("[+] Server listening on port {} [+]\n".format(port)) connected_clients = [] while True: requested_connexions, wlist, xlist = select.select([soc], [], [], 0.05) for co in requested_connexions: connexion, infos = soc.accept() print("New connection from {}:{}".format(infos[0], infos[1])) connected_clients.append(connexion) ready_clients = [] try: ready_clients, wlist, xlist = select.select(connected_clients, [], [], 0.05) except select.error: pass else: for client in ready_clients: rcv = client.recv(2048)
def get_data(self): if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): return sys.stdin.read(1) return False
freq = None base_dir = _os.path.dirname(_os.path.realpath(__file__)) with gzip.open(_os.path.join(base_dir, "../dictionaries/fr/reaccentue.pz"), 'rb') as dico_cache: dico = pickle.load(dico_cache) articles = ['le', 'la', 'les', 'un', 'une', 'des', 'à', 'au', 'aux', 'du', 'de', 'et', 'ou'] if __name__ == "__main__": if len(sys.argv) == 1: if select.select([sys.stdin, ], [], [], 0.0)[0]: lines = sys.stdin.readlines() for l in lines: print(reaccentue(l.replace('\n', ''))) else: print("""Usage: reaccentue.py texte ou fichier reaccentue.py 'BOULEVARD DU MARECHAL JEAN MARIE DE LATTRE DE TASSIGNY' reaccentue.py fichier.csv nom_colonne""") else: if bool(re.search('.csv$', sys.argv[1])): with open(sys.argv[1], 'r') as in_file: csv_in = csv.DictReader(in_file) csv_out = csv.DictWriter(sys.stdout, fieldnames=csv_in.fieldnames) csv_out.writerow(dict((fn, fn) for fn in csv_in.fieldnames)) for row in csv_in:
def run(self): rc = 0 while self.keep_running and (rc >= 0): readable, writable, exceptional = select.select( [self.sock_a, self.sock_b], [], [self.sock_a, self.sock_b], 5.0) in_a = None in_b = None data_a = bytearray() data_b = bytearray() flag_a = -1 flag_b = -1 # Check for select() polling timeout and pcm self-check if (not readable) and (not writable) and (not exceptional): rc = self.pcm.check() if isinstance(rc, ctypes.c_int): rc = rc.value continue # Data received on the udp port is 320 bytes for an audio frame or 2 bytes for a flag if self.sock_a in readable: in_a = self.sock_a.recvfrom(MAX_SUPERFRAME_SIZE) if self.sock_b in readable: in_b = self.sock_b.recvfrom(MAX_SUPERFRAME_SIZE) if in_a is not None: len_a = len(in_a[0]) if len_a == 2: flag_a = np.frombuffer(in_a[0], dtype=np.int16)[0] elif len_a > 0: data_a = in_a[0] if in_b is not None: len_b = len(in_b[0]) if len_b == 2: flag_b = np.frombuffer(in_b[0], dtype=np.int16)[0] elif len_b > 0: data_b = in_b[0] if (flag_a == 0) or (flag_b == 0): rc = self.pcm.drain() if isinstance(rc, ctypes.c_int): rc = rc.value continue if (((flag_a == 1) and (flag_b == 1)) or ((flag_a == 1) and (in_b is None)) or ((flag_b == 1) and (in_a is None))): rc = self.pcm.drop() if isinstance(rc, ctypes.c_int): rc = rc.value continue if not self.two_channels: data_a = self.scale(data_a) rc = self.pcm.write(self.interleave(data_a, data_a)) if isinstance(rc, ctypes.c_int): rc = rc.value else: data_a = self.scale(data_a) data_b = self.scale(data_b) rc = self.pcm.write(self.interleave(data_a, data_b)) if isinstance(rc, ctypes.c_int): rc = rc.value self.close_sockets() self.close_pcm() return
def _fileno_can_read(fileno): """Check if a file descriptor is readable.""" return len(select.select([fileno], [], [], 0)[0]) > 0
def manage_createBackup(self, includeEvents=None, includeMysqlLogin=None, timeout=120, REQUEST=None, writeMethod=None): """ Create a new backup file using zenbackup and the options specified in the request. This method makes use of the fact that DataRoot is a Commandable in order to use Commandable.write """ import popen2 import fcntl import time import select def write(s): if writeMethod: writeMethod(s) elif REQUEST: self.write(REQUEST.RESPONSE, s) footer = None if REQUEST and not writeMethod: header, footer = self.commandOutputTemplate().split('OUTPUT_TOKEN') REQUEST.RESPONSE.write(str(header)) write('') try: cmd = binPath('zenbackup') + ' -v10' if not includeEvents: cmd += ' --no-eventsdb' if not includeMysqlLogin: cmd += ' --no-save-mysql-access' try: timeout = int(timeout) except ValueError: timeout = 120 timeout = max(timeout, 1) child = popen2.Popen4(cmd) flags = fcntl.fcntl(child.fromchild, fcntl.F_GETFL) fcntl.fcntl(child.fromchild, fcntl.F_SETFL, flags | os.O_NDELAY) endtime = time.time() + timeout write('%s' % cmd) write('') pollPeriod = 1 firstPass = True while time.time() < endtime and (firstPass or child.poll() == -1): firstPass = False r, w, e = select.select([child.fromchild], [], [], pollPeriod) if r: t = child.fromchild.read() # We are sometimes getting to this point without any data # from child.fromchild. I don't think that should happen # but the conditional below seems to be necessary. if t: write(t) if child.poll() == -1: write('Backup timed out after %s seconds.' % timeout) import signal os.kill(child.pid, signal.SIGKILL) write('DONE') except Exception: write('Exception while performing backup.') write('type: %s value: %s' % tuple(sys.exc_info()[:2])) else: if REQUEST or writeMethod: audit('UI.Backup.Create') write('') if REQUEST and footer: REQUEST.RESPONSE.write(footer)
remotePort = int(remotePort) localPort = int(localPort) ports.append((host, remotePort, localPort)) else: ports.append(("localhost", int(arg), int(arg))) except: parser.print_help() sys.exit(1) servers = [] for host, remotePort, localPort in ports: print "Forwarding local port {0}:{1} to remote port {2}".format( host, localPort, remotePort) server = serverClass((host, localPort), TCPRelay) server.remotePort = remotePort server.bufferSize = options.bufsize server.devices = devices servers.append(server) alive = True while alive: try: rl, wl, xl = select.select(servers, [], []) for server in rl: server.handle_request() except: traceback.print_exc() alive = False
def main(): # Извлекает ip-адрес и порт из командной строки listen_addr, listen_port = parse_cmd_arguments() # Создает TCP-сокет сервера server_tcp = socket(AF_INET, SOCK_STREAM) # Связывает сокет с ip-адресом и портом сервера server_tcp.bind((listen_addr, listen_port)) # Таймаут для операций с сокетом server_tcp.settimeout(0.5) # Запускает режим прослушивания server_tcp.listen(MAX_CONNECTIONS) SERVER_LOGGER.info(f'Запущен сервер, порт для подключений: {listen_port}, ' f'адрес с которого принимаются подключения: {listen_addr}. ' f'Если адрес не указан, принимаются соединения с любых адресов.') print(f'Запущен сервер, порт для подключений: {listen_port}, ' f'адрес с которого принимаются подключения: {listen_addr}.') # Список клиентов и очередь сообщений all_clients = [] all_messages = [] # Словарь зарегистрированных клиентов: ключ - имя пользователя, значение - сокет all_names = dict() while True: # Принимает запрос на соединение # Возвращает кортеж (новый TCP-сокет клиента, адрес клиента) try: client_tcp, client_addr = server_tcp.accept() except OSError: pass else: SERVER_LOGGER.info(f'Установлено соедение с клиентом {client_addr}') print(f'Установлено соедение с клиентом {client_addr}') all_clients.append(client_tcp) r_clients = [] w_clients = [] errs = [] # Запрашивает информацию о готовности к вводу, выводу и о наличии исключений для группы дескрипторов сокетов try: if all_clients: r_clients, w_clients, errs = select.select(all_clients, all_clients, [], 0) except OSError: pass # Чтение запросов из списка клиентов if r_clients: for r_sock in r_clients: try: parse_client_msg(receive_message(r_sock), all_messages, r_sock, all_clients, all_names) except Exception as ex: SERVER_LOGGER.error(f'Клиент отключился от сервера. ' f'Тип исключения: {type(ex).__name__}, аргументы: {ex.args}') all_clients.remove(r_sock) # Роутинг сообщений адресатам for msg in all_messages: try: route_client_msg(msg, all_names, w_clients) except Exception: SERVER_LOGGER.info(f'Связь с клиентом {msg[DESTINATION]} была потеряна') all_clients.remove(all_names[msg[DESTINATION]]) del all_names[msg[DESTINATION]] all_messages.clear()
#Need explanation #{} means it is a set, no duplicate, not ordered (not tuple,not list,not dictionary) message_queues = {} #inputs is not empty, so, enter the loop #for any reason, server-input is to be closed, while loop will exit while inputs: #select blocks untill there is activity in one of the fd passed to it print('Just before select()') print('monitoring....') print_fd('inputs:', inputs) print_fd('outputs:', outputs) print_fd('errors:', errors) readable, writable, exceptional = select.select(inputs, outputs, errors) #if server-socket receive any request, it is readable print('Just exited select()') #php foreach-as-key-value type of loop #print('Monitoring:\nInputs{}\nOutputs{}\n'.format(inputs,outputs)) print('Actions occured in....') print_fd('readable:', readable) print_fd('writable:', writable) print_fd('exceptional:', exceptional) #print('Actions occured in:\nreadable{}\nwritable{}\nexceptional{}\n'.format(inputs,outputs,exceptional)) for s in readable:
def multiselect(r_fds, w_fds, x_fds, timeout=None, limit=MAX_SELECT_SOCKETS): fds = [] for fd in r_fds + w_fds + x_fds: if fd not in fds: fds.append(fd) # if we're using less than the limit, fall back to regular select if len(fds) < limit: return select.select(r_fds, w_fds, x_fds, timeout) # divide the fd sets into groups of max MAX_SELECT_SOCKETS sets fdsets = [] while fds: fds_ = fds[:limit] fds = fds[limit:] fdsets.append(([fd for fd in fds_ if fd in r_fds], [fd for fd in fds_ if fd in w_fds], [fd for fd in fds_ if fd in x_fds])) # the return fd sets r_r_fds = [] r_w_fds = [] r_x_fds = [] # first, run a cycle over all threads with a 0 timeout to prevent starvation for fdset in fdsets: r, w, x = select.select(fdset[0], fdset[1], fdset[2], 0) r_r_fds += r r_w_fds += w r_x_fds += x # if we have anything to return, return it. also return if the timeout is 0 if r_r_fds or r_w_fds or r_x_fds or (timeout == 0): return r_r_fds, r_w_fds, r_x_fds # here's where things get hairy: more than MAX_SELECT_SOCKETS sockets, # a non-zero timeout and no immediately available sockets # done_event will be set once a select thread detects workable sockets done_event = threading.Event() # a lock to prevent race conditions when appending to the return fd sets lock = _thread.allocate_lock() # the select thread def thread_select(r_fds, w_fds, x_fds, r_r_fds, r_w_fds, r_x_fds, lock, done_event): # call select with the specified timeout r, w, x = select.select(r_fds, w_fds, x_fds, timeout) # acquire the lock lock.acquire() # append our sockets to the return sets r_r_fds += r r_w_fds += w r_x_fds += x # release our lock lock.release() # set the event to indicicate that we have socket ready done_event.set() # start the select threads for fdset in fdsets: _thread.start_new_thread(thread_select, fdset + (r_r_fds, r_w_fds, r_x_fds, lock, done_event)) # wait for one of the threads to complete done_event.wait(timeout) # acquire the lock lock.acquire() # collect the return data ret = (r_r_fds, r_w_fds, r_x_fds) # release the lock lock.release() # return our data return ret
import socket import select # Buffer size BUFFER = 1024 # Listen on port 5678 # (to all IP addresses on this system) #listen_addr = ("",5678) sockets = [] for port in range(6000, 6101): server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind(('', port)) sockets.append(server_socket) while True: readable, writable, exceptional = select.select(sockets, [], []) for s in readable: (data, addr) = s.recvfrom(BUFFER) s.sendto(data, addr) for s in sockets: s.close()
def __enter__(self): self.temp_dir_mgr = None temp_dir_mgr = _TempDirManager() try: working_dir = temp_dir_mgr.path from os.path import join, abspath, exists if isinstance(self.source, ScriptSource): source_file_name = join(working_dir, "temp." + self.source.extension) with open(source_file_name, "w") as source_file: source_file.write(self.source.source) elif isinstance(self.source, FileSource): source_file_name = abspath(self.source.filename) if not exists(source_file_name): raise IOError("'%s' does not exist" % source_file_name) elif isinstance(self.source, ScriptWithFilesSource): source_file_name = join(working_dir, self.source.source_name) with open(source_file_name, "w") as source_file: source_file.write(self.source.source) from os.path import basename from shutil import copyfile for f in self.source.filenames: copyfile(f, join(working_dir, basename(f))) else: raise RuntimeError("'source' type unrecognized") output_file_name = join(working_dir, self.output_file_name) cmdline = [ self.gmsh_executable, "-o", self.output_file_name, "-nopopup", "-format", "msh2" ] # NOTE: handle unit incompatibility introduced in GMSH4 # https://gitlab.onelab.info/gmsh/gmsh/issues/397 if self.version < '4.0.0': if self.target_unit == 'M': cmdline.extend(["-string", "Geometry.OCCScaling=1000;"]) else: cmdline.extend([ "-string", "Geometry.OCCTargetUnit='{}';".format(self.target_unit) ]) if self.dimensions is not None: cmdline.append("-%d" % self.dimensions) if self.order is not None: cmdline.extend(["-order", str(self.order)]) if self.incomplete_elements is not None: cmdline.extend([ "-string", "Mesh.SecondOrderIncomplete = %d;" % int(self.incomplete_elements) ]) cmdline.extend(self.other_options) cmdline.append(source_file_name) if self.dimensions is None: cmdline.append("-") logger.info("invoking gmsh: '%s'" % " ".join(cmdline)) from pytools.prefork import call_capture_output retcode, stdout, stderr = call_capture_output(cmdline, working_dir) logger.info("return from gmsh") stdout = stdout.decode("utf-8") stderr = stderr.decode("utf-8") import re error_match = re.match(r"([0-9]+)\s+error", stdout) warning_match = re.match(r"([0-9]+)\s+warning", stdout) if error_match is not None or warning_match is not None: # if we have one, we expect to see both assert error_match is not None or warning_match is not None num_warnings = int(warning_match.group(1)) num_errors = int(error_match.group(1)) else: num_warnings = 0 num_errors = 0 if num_errors: msg = "gmsh execution failed with message:\n\n" if stdout: msg += stdout + "\n" msg += stderr + "\n" raise GmshError(msg) if num_warnings: from warnings import warn msg = "gmsh issued the following warning messages:\n\n" if stdout: msg += stdout + "\n" msg += stderr + "\n" warn(msg) self.output_file = open(output_file_name, "r") if self.save_tmp_files_in: import shutil import errno try: shutil.copytree(working_dir, self.save_tmp_files_in) except FileExistsError: import select import sys print( "%s exists! Overwrite? (Y/N, will default to Y in 10sec)." % self.save_tmp_files_in) decision = None while decision is None: i, o, e = select.select([sys.stdin], [], [], 10) if i: resp = sys.stdin.readline().strip() if resp == "N" or resp == "n": logger.info("Not overwriting.") decision = 0 elif resp == "Y" or resp == "y" or not i: decision = 1 logger.info("Overwriting.") else: print("Illegal input %s, please retry." % i) else: decision = 1 # default if decision == 0: pass else: assert decision == 1 shutil.rmtree(self.save_tmp_files_in) shutil.copytree(working_dir, self.save_tmp_files_in) except OSError as exc: if exc.errno == errno.ENOTDIR: shutil.copy( output_file_name, '/'.join([ self.save_tmp_files_in, self.output_file_name ])) else: raise self.temp_dir_mgr = temp_dir_mgr return self except Exception: temp_dir_mgr.clean_up() raise
try: if not command[1] or not command[2]: print("Invalid command.\nSyntax: newuser <username> <password>") continue else: server.send(' '.join(command)) except: print("Invalid command.\nSyntax: newuser <username> <password>") continue # set check variable to True, repeat below loop until it is false check = True while check: # establish inputs as the server's messages and keyboard input and listen on them socketList = [sys.stdin, server] readSockets,writeSocket,errorSocket = select.select(socketList,[],[]) for socks in readSockets: # if the message is from the server if socks == server: # receive the message from the server message = socks.recv(2048) # if the message is a status message (preceded with a '|'), handle the status message. if message == "|login-success": print("Welcome to the Chatroom!") elif message == "|login-syntaxerror": print("Invalid command.\nSyntax: login <username> <password>") server.close() check = False break
def quiz(): question_number = 0 sendtoall("\nWelcome to QUIZ MASTERS.\n\n" "Rules:\n" "1. On receiving the question, each player is given 10 seconds to press the buzzer. \n" "2. The first one to press the buzzer gets a chance to provide the answer within 10 seconds.\n" "3. If the answer is correct, the player gets 1 point. Otherwise, the player gets -0.5. \n" "4. The first player to reach 5 points, wins the quiz.\n\n") while max(scores) < 5: print("\nRound " + str(question_number + 1) + ":") sendtoall("\nQuestion number: " + str(question_number + 1) + '\n') sendtoall(questions[question_number]) sendtoall("\nPress enter key for buzzer.\n") readable, writable, exceptional = select.select(clients, [], [], 10) if readable: first_client = readable[0] client_number = identify_client(first_client) answering_client = [first_client] buzzer = first_client.recv(10) while buzzer == '\n': pass print("Player" + str(client_number + 1) + " pressed the buzzer first.") sendexcept(first_client, " Player " + str(client_number + 1) + " pressed the buzzer first.\n") first_client.send(bytes("Enter correct option (in lower case and press enter key) :\n", "utf-8")) read, write, exception = select.select(answering_client, [], [], 10) if read: answer = first_client.recv(10) while answer == '\n': pass answer = str(answer, 'utf-8') print("Player" + str(client_number + 1) + "'s answer: " + answer[0]) if answer[0] == answers[question_number]: scores[client_number] += 1 first_client.send(bytes("\n Correct answer(+1). Your score:" + str(scores[client_number]) + "\n", "utf-8")) else: scores[client_number] -= 0.5 first_client.send(bytes("\n Wrong answer(-0.5). Your score:" + str(scores[client_number]) + "\n", "utf-8")) else: first_client.send(bytes(" Time up...\n", "utf-8")) else: sendtoall("\n No player pressed the buzzer.\n\n") sendtoall("\n Scores after round " + str(question_number + 1) + ":\n Player 1: " + str(scores[0]) + "\n Player 2: " + str(scores[1]) + "\n Player 3: " + str(scores[2]) + "\n\n") readable, writable, exceptional = select.select(clients, [], [], 0.25) while readable: c = readable[0] c.recv(10) readable, writable, exceptional = select.select(clients, [], [], 0.25) question_number += 1 if question_number == 50: sendtoall(" GAME OVER!\n There is no winner. " + "\n\n") print("\n GAME OVER!\n There is no winner. " + "\n\n") sendtoall("Exit") break if max(scores) >= 5: sendtoall(" GAME OVER!\n The winner is Player " + str(scores.index(max(scores))+1) + "\n\n") print("\n GAME OVER!\n The winner is Player " + str(scores.index(max(scores))+1) + "\n\n") sendtoall("Exit")
def posix_shell(self): """ Use paramiko channel connect server interactive. 使用paramiko模块的channel,连接后端,进入交互式 """ log_file_f, log_time_f, log = self.get_log() termlog = TermLogRecorder(User.objects.get(id=self.user.id)) termlog.setid(log.id) old_tty = termios.tcgetattr(sys.stdin) pre_timestamp = time.time() data = '' input_mode = False try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) self.channel.settimeout(0.0) while True: try: r, w, e = select.select([self.channel, sys.stdin], [], []) flag = fcntl.fcntl(sys.stdin, fcntl.F_GETFL, 0) fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag | os.O_NONBLOCK) except Exception: pass if self.channel in r: try: x = self.channel.recv(10240) if len(x) == 0: break index = 0 len_x = len(x) while index < len_x: try: n = os.write(sys.stdout.fileno(), x[index:]) sys.stdout.flush() index += n except OSError as msg: if msg.errno == errno.EAGAIN: continue now_timestamp = time.time() termlog.write(x) termlog.recoder = False log_time_f.write( '%s %s\n' % (round(now_timestamp - pre_timestamp, 4), len(x))) log_time_f.flush() log_file_f.write(x) log_file_f.flush() pre_timestamp = now_timestamp log_file_f.flush() self.vim_data += x if input_mode: data += x except socket.timeout: pass if sys.stdin in r: try: x = os.read(sys.stdin.fileno(), 4096) except OSError: pass termlog.recoder = True input_mode = True if self.is_output(str(x)): # 如果len(str(x)) > 1 说明是复制输入的 if len(str(x)) > 1: data = x match = self.vim_end_pattern.findall(self.vim_data) if match: if self.vim_flag or len(match) == 2: self.vim_flag = False else: self.vim_flag = True elif not self.vim_flag: self.vim_flag = False data = self.deal_command(data)[0:200] if data is not None: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() data = '' self.vim_data = '' input_mode = False if len(x) == 0: break self.channel.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty) log_file_f.write('End time is %s' % datetime.datetime.now()) log_file_f.close() log_time_f.close() termlog.save() log.filename = termlog.filename log.is_finished = True log.end_time = datetime.datetime.now() log.save()