本文整理汇总了Python中select.select函数的典型用法代码示例。如果您正苦于以下问题:Python select函数的具体用法?Python select怎么用?Python select使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了select函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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')
示例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()
示例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__,))
示例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
示例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)
示例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
示例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
示例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('')
示例10: test_select1
def test_select1(self):
import select
import socket
s1, s2 = socket.socketpair()
with hub.Timeout(1, MyException):
select.select([s2.fileno()], [], [])
示例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
示例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
示例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
示例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
示例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)