• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python select.select函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中select.select函数的典型用法代码示例。如果您正苦于以下问题:Python select函数的具体用法?Python select怎么用?Python select使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了select函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: sendMsg

    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
开发者ID:andychen,项目名称:SmootLight,代码行数:32,代码来源:TapRunningInstallation.py


示例2: processInput

    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')
开发者ID:liuriloami,项目名称:ahl-coderprize,代码行数:25,代码来源:ajp_base.py


示例3: _connect

    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()
开发者ID:chenkaigithub,项目名称:floobits-sublime,代码行数:25,代码来源:agent_connection.py


示例4: handle_until_return

 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__,))
开发者ID:antoine1fr,项目名称:pygirl,代码行数:32,代码来源:sandlib.py


示例5: _select

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
开发者ID:jarieb,项目名称:celery,代码行数:26,代码来源:processes.py


示例6: getCommandOutput2

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)
开发者ID:PivotalBigData,项目名称:incubator-hawq,代码行数:34,代码来源:utils.py


示例7: write

 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
开发者ID:adamfeuer,项目名称:pyftdi,代码行数:26,代码来源:protocol_unix.py


示例8: wait_child

    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
开发者ID:Ebsy,项目名称:RootFS-RaspberryPI,代码行数:26,代码来源:base.py


示例9: __init__

    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('')
开发者ID:Gwildor,项目名称:Pyromancer,代码行数:27,代码来源:objects.py


示例10: test_select1

    def test_select1(self):
        import select
        import socket

        s1, s2 = socket.socketpair()
        with hub.Timeout(1, MyException):
            select.select([s2.fileno()], [], [])
开发者ID:5g-empower,项目名称:empower-ryu,代码行数:7,代码来源:test_hub.py


示例11: shell_call

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
开发者ID:ihoney,项目名称:incubator-trafodion,代码行数:30,代码来源:jdbc_test.py


示例12: handle_write

 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
开发者ID:rcarmo,项目名称:spdy-http,代码行数:28,代码来源:push_tcp.py


示例13: forward_data

    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
开发者ID:Aaron-P,项目名称:weevely3,代码行数:32,代码来源:tcpserver.py


示例14: getKey

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
开发者ID:rdiverdi,项目名称:comprobo15,代码行数:7,代码来源:teleop2.py


示例15: run

  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)
开发者ID:5a2v0,项目名称:YunBridge,代码行数:27,代码来源:tcp.py


示例16: run

    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())
开发者ID:yaba,项目名称:SMTPProxy,代码行数:34,代码来源:smtpproxy.py


示例17: receive

    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)
开发者ID:zhilinwww,项目名称:Bismuth,代码行数:32,代码来源:connections.py


示例18: run

 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")
开发者ID:benthor,项目名称:remotty,代码行数:25,代码来源:pttypipe.py


示例19: poll

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()
开发者ID:adamkiczula,项目名称:anaconda,代码行数:33,代码来源:ioloop.py


示例20: _connect

    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
开发者ID:Floobits,项目名称:floobits-emacs,代码行数:27,代码来源:floo_proto.py



注:本文中的select.select函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python selectBrowser._getBrowser函数代码示例发布时间:2022-05-27
下一篇:
Python select.poll函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap