本文整理汇总了Python中asyncio.queues.Queue.get_nowait方法的典型用法代码示例。如果您正苦于以下问题:Python Queue.get_nowait方法的具体用法?Python Queue.get_nowait怎么用?Python Queue.get_nowait使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio.queues.Queue
的用法示例。
在下文中一共展示了Queue.get_nowait方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Core
# 需要导入模块: from asyncio.queues import Queue [as 别名]
# 或者: from asyncio.queues.Queue import get_nowait [as 别名]
class Core(object):
def __init__(self, bot):
self.bot = bot
self.timeout = int(self.bot.config.get('timeout'))
self.ping_queue = Queue(loop=bot.loop)
def connection_made(self):
self.bot.loop.call_later(self.timeout, self.check_ping)
self.ping_queue.put_nowait(self.bot.loop.time())
def check_ping(self): # pragma: no cover
# check if we received a ping
# reconnect if queue is empty
self.bot.log.debug(
'Ping queue size: {}'.format(self.ping_queue.qsize()))
if self.ping_queue.empty():
self.bot.loop.call_soon(self.bot.protocol.transport.close)
else:
self.bot.loop.call_later(self.timeout, self.check_ping)
while not self.ping_queue.empty():
self.ping_queue.get_nowait()
@event(rfc.PING)
def pong(self, data):
"""PING reply"""
self.ping_queue.put_nowait(self.bot.loop.time())
self.bot.send('PONG ' + data)
@event(rfc.NEW_NICK)
def recompile(self, nick=None, new_nick=None, **kw):
"""recompile regexp on new nick"""
if self.bot.nick == nick.nick:
self.bot.config['nick'] = new_nick
self.bot.recompile()
@event(rfc.ERR_NICK)
def badnick(self, me=None, nick=None, **kw):
"""Use alt nick on nick error"""
if me == '*':
self.bot.set_nick(self.bot.nick + '_')
self.bot.log.debug('Trying to regain nickname in 30s...')
self.bot.loop.call_later(30, self.bot.set_nick, self.bot.original_nick)
@event(rfc.RPL_ENDOFMOTD)
def autojoin(self, **kw):
"""autojoin at the end of MOTD"""
self.bot.config['nick'] = kw['me']
self.bot.recompile()
channels = utils.as_list(self.bot.config.get('autojoins', []))
for channel in channels:
channel = utils.as_channel(channel)
self.bot.log.info('Trying to join %s', channel)
self.bot.join(channel)
示例2: IrcConnection
# 需要导入模块: from asyncio.queues import Queue [as 别名]
# 或者: from asyncio.queues.Queue import get_nowait [as 别名]
class IrcConnection(asyncio.Protocol):
"""asyncio protocol to handle an irc connection"""
def connection_made(self, transport):
self.transport = transport
self.closed = False
self.queue = Queue()
def data_received(self, data):
encoding = getattr(self, 'encoding', 'ascii')
data = data.decode(encoding, 'ignore')
if not self.queue.empty():
data = self.queue.get_nowait() + data
lines = data.split('\r\n')
self.queue.put_nowait(lines.pop(-1))
for line in lines:
self.factory.dispatch(line)
def write(self, data):
if data is not None:
if isinstance(data, text_type):
data = data.encode(self.encoding)
if not data.endswith(b'\r\n'):
data = data + b'\r\n'
self.transport.write(data)
def connection_lost(self, exc): # pragma: no cover
self.factory.log.critical('connection lost (%s): %r',
id(self.transport),
exc)
self.factory.notify('connection_lost')
if not self.closed:
self.close()
# wait a few before reconnect
self.factory.loop.call_later(
2, self.factory.create_connection, self.__class__)
def close(self): # pragma: no cover
if not self.closed:
self.factory.log.critical('closing old transport (%r)',
id(self.transport))
try:
self.transport.close()
finally:
self.closed = True
示例3: __init__
# 需要导入模块: from asyncio.queues import Queue [as 别名]
# 或者: from asyncio.queues.Queue import get_nowait [as 别名]
class StreamConnection:
def __init__(self, sr, sw, *, loop=None):
if not loop:
loop = asyncio.get_event_loop()
self._loop = loop
self._sr = sr
self._sw = sw
self._msgs = Queue(loop=loop)
self._worker = loop.create_task(self._run())
@asyncio.coroutine
def _run(self):
while self.alive():
try:
data = yield from self._sr.readline()
if data and len(data):
self._msgs.put_nowait(self._convert(data))
except asyncio.CancelledError:
logger.debug("readline from stream reader was cancelled.")
except ConnectionError:
logger.debug("connection error")
break
logger.debug("connection closed")
def _convert(self, data):
return data.strip()
@asyncio.coroutine
def recv(self):
try:
return self._msgs.get_nowait()
except QueueEmpty:
pass
# Wait for a message until the connection is closed
next_message = self._loop.create_task(self._msgs.get())
done, pending = yield from asyncio.wait(
[next_message, self._worker],
loop=self._loop, return_when=asyncio.FIRST_COMPLETED)
if next_message in done:
return next_message.result()
else:
next_message.cancel()
def send(self, data):
if not self.alive():
raise ConnectionError("connection was closed.")
try:
data = data + b'\n'
self._sw.write(data)
except OSError:
raise ConnectionError("can't send data.")
except Exception:
logger.debug("Q___Q")
def alive(self):
return not self._sr.at_eof()
@asyncio.coroutine
def drain():
yield from self._sw.drain()
@asyncio.coroutine
def close(self):
if self.alive():
try:
yield from self._sw.drain()
self._sw.write_eof()
except ConnectionError:
pass
else:
self._sr.feed_eof()
self._sw.close()
self._worker.cancel()
示例4: WebSocketCommonProtocol
# 需要导入模块: from asyncio.queues import Queue [as 别名]
# 或者: from asyncio.queues.Queue import get_nowait [as 别名]
#.........这里部分代码省略.........
The `code` must be an :class:`int` and the `reason` a :class:`str`.
"""
if self.state == 'OPEN':
# 7.1.2. Start the WebSocket Closing Handshake
self.close_code, self.close_reason = code, reason
yield from self.write_frame(OP_CLOSE, serialize_close(code, reason))
# 7.1.3. The WebSocket Closing Handshake is Started
self.state = 'CLOSING'
# If the connection doesn't terminate within the timeout, break out of
# the worker loop.
try:
yield from asyncio.wait_for(self.worker, timeout=self.timeout)
except asyncio.TimeoutError:
self.worker.cancel()
# The worker should terminate quickly once it has been cancelled.
yield from self.worker
@asyncio.coroutine
def recv(self):
"""
This coroutine receives the next message.
It returns a :class:`str` for a text frame and :class:`bytes` for a
binary frame.
When the end of the message stream is reached, or when a protocol
error occurs, :meth:`recv` returns ``None``, indicating that the
connection is closed.
"""
# Return any available message
try:
return self.messages.get_nowait()
except QueueEmpty:
pass
# Wait for a message until the connection is closed
next_message = asyncio.async(self.messages.get())
done, pending = yield from asyncio.wait(
[next_message, self.worker],
return_when=asyncio.FIRST_COMPLETED)
if next_message in done:
return next_message.result()
else:
next_message.cancel()
@asyncio.coroutine
def send(self, data):
"""
This coroutine sends a message.
It sends a :class:`str` as a text frame and :class:`bytes` as a binary
frame.
It raises a :exc:`TypeError` for other inputs and
:exc:`InvalidState` once the connection is closed.
"""
if isinstance(data, str):
opcode = 1
data = data.encode('utf-8')
elif isinstance(data, bytes):
opcode = 2
else:
raise TypeError("data must be bytes or str")
yield from self.write_frame(opcode, data)