本文整理匯總了Python中curio.spawn方法的典型用法代碼示例。如果您正苦於以下問題:Python curio.spawn方法的具體用法?Python curio.spawn怎麽用?Python curio.spawn使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類curio
的用法示例。
在下文中一共展示了curio.spawn方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: thread_handler
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def thread_handler():
'''
Special handler function that allows Curio to respond to
threads that want to access async functions. This handler
must be spawned manually in code that wants to allow normal
threads to promote to Curio async threads.
'''
global _request_queue
assert _request_queue is None, "thread_handler already running"
_request_queue = queue.UniversalQueue()
try:
while True:
request, thr, fut = await _request_queue.get()
if request == 'start':
athread = AsyncThread(None)
athread._task = await spawn(athread._coro_runner, daemon=True)
athread._thread = thr
fut.set_result(athread)
elif request == 'stop':
thr._request.set_result(None)
await thr._task.join()
fut.set_result(None)
finally:
_request_queue = None
示例2: cmd_associate
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def cmd_associate(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.bind(("", 0))
host, port = sock.getsockname()
async with sock:
await self._stream.write(self._make_resp(host=host, port=port))
task = await spawn(self.relay_udp(sock))
while True:
data = await self._stream.read()
if not data:
await task.cancel()
return
if verbose > 0:
print("receive unexpect data:", data)
except Exception:
sock._socket.close()
示例3: h2_server
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def h2_server(address, root, certfile, keyfile):
"""
Create an HTTP/2 server at the given address.
"""
sock = await create_listening_ssl_socket(address, certfile, keyfile)
print("Now listening on %s:%d" % address)
async with sock:
while True:
client, _ = await sock.accept()
server = H2Server(client, root)
await spawn(server.run())
示例4: run
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def run(self):
"""
Loop over the connection, managing it appropriately.
"""
self.conn.initiate_connection()
await self.sock.sendall(self.conn.data_to_send())
while True:
# 65535 is basically arbitrary here: this amounts to "give me
# whatever data you have".
data = await self.sock.recv(65535)
if not data:
break
events = self.conn.receive_data(data)
for event in events:
if isinstance(event, h2.events.RequestReceived):
await spawn(
self.request_received(event.headers, event.stream_id)
)
elif isinstance(event, h2.events.DataReceived):
self.conn.reset_stream(event.stream_id)
elif isinstance(event, h2.events.WindowUpdated):
await self.window_updated(event)
await self.sock.sendall(self.conn.data_to_send())
示例5: bricknil_socket_server
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def bricknil_socket_server(web_out_queue, address): #pragma: no cover
"""Listen for client connections on port 25000 and spawn
`WebClient` instance.
This fuction is spawned as a task during system instantiation
in :func:`bricknil.bricknil._run_all``
"""
async def web_client_connected(client, addr):
logger.info('connection from', addr)
wc = WebClient(client, addr, web_out_queue)
await wc.run()
task = await spawn(tcp_server, '', 25000, web_client_connected, daemon=True)
示例6: _emit_control
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def _emit_control(self, data, hub, hub_stop_evt, ble, sensor):
async def dummy():
pass
system = await spawn(bricknil.bricknil._run_all(ble, dummy))
while not hub.peripheral_queue:
await sleep(0.1)
#await sleep(3)
port = data.draw(st.integers(0,254))
await hub.peripheral_queue.put( ('attach', (port, sensor.sensor_name)) )
# Now, make sure the sensor sent an activate updates message
if sensor.sensor_name == "Button":
await self._wait_send_message(sensor.send_message, 'Activate button')
else:
await self._wait_send_message(sensor.send_message, 'Activate SENSOR')
# Need to generate a value on the port
# if False:
msg = []
if len(sensor.capabilities) == 1:
# Handle single capability
for cap in sensor.capabilities:
n_datasets, byte_count = sensor.datasets[cap][0:2]
for i in range(n_datasets):
for b in range(byte_count):
msg.append(data.draw(st.integers(0,255)))
msg = bytearray(msg)
await hub.peripheral_queue.put( ('value_change', (port, msg)))
elif len(sensor.capabilities) > 1:
modes = 1
msg.append(modes)
for cap_i, cap in enumerate(sensor.capabilities):
if modes & (1<<cap_i):
n_datasets, byte_count = sensor.datasets[cap][0:2]
for i in range(n_datasets):
for b in range(byte_count):
msg.append(data.draw(st.integers(0,255)))
msg = bytearray(msg)
await hub.peripheral_queue.put( ('value_change', (port, msg)))
await hub_stop_evt.set()
await system.join()
示例7: main
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def main(host, port):
# Starting the client
cli_task = await curio.spawn(ping_observing_task, (host, port))
await cli_task.join()
# ==============================================================================
示例8: supervisor
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def supervisor(): # <6>
spinner = await curio.spawn(spin('thinking!')) # <7>
print('spinner object:\n ', repr(spinner)) # <8>
result = await slow_function() # <9>
await spinner.cancel() # <10>
return result
示例9: main_coro
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def main_coro():
# await curio.spawn(print_memory_growth_statistics(), daemon=True)
async with purerpc.insecure_channel("localhost", 50055) as channel:
for i in range(100):
start = time.time()
async with curio.TaskGroup() as task_group:
for i in range(100):
await task_group.spawn(worker(channel))
print("RPS: {}".format(10000 / (time.time() - start)))
示例10: spawn
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def spawn(self, callable, *args, daemon=False):
t = AWAIT(curio.spawn_thread, callable, *args, daemon=daemon)
AWAIT(self._tg.add_task, t)
return Thread(t)
示例11: run
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def run(callable, *args):
async def _runner():
t = await curio.spawn(thr.thread_handler)
try:
async with curio.spawn_thread():
return callable(*args)
finally:
await t.cancel()
return curio.run(_runner)
示例12: relay
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def relay(self, addr, sendfrom):
if self._task is None:
self._task = await curio.spawn(self._relay, addr, sendfrom)
示例13: relay
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def relay(self, remote_stream):
t1 = await spawn(self._relay(self._stream, remote_stream))
t2 = await spawn(self._relay2(remote_stream, self._stream))
try:
async with TaskGroup([t1, t2]) as g:
task = await g.next_done()
await task.join()
await g.cancel_remaining()
except CancelledError:
pass
示例14: test_run_hub_with_bleak
# 需要導入模塊: import curio [as 別名]
# 或者: from curio import spawn [as 別名]
def test_run_hub_with_bleak(self, data):
Hub.hubs = []
sensor_name = 'sensor'
sensor = data.draw(st.sampled_from(self.sensor_list))
capabilities = self._draw_capabilities(data, sensor)
hub_type = data.draw(st.sampled_from(self.hub_list))
TestHub, stop_evt = self._get_hub_class(hub_type, sensor, sensor_name, capabilities)
hub = TestHub('test_hub')
async def dummy():
pass
# Start the hub
#MockBleak = MagicMock()
sys.modules['bleak'] = MockBleak(hub)
with patch('bricknil.bricknil.USE_BLEAK', True), \
patch('bricknil.ble_queue.USE_BLEAK', True) as use_bleak:
sensor_obj = getattr(hub, sensor_name)
sensor_obj.send_message = Mock(side_effect=coroutine(lambda x,y: "the awaitable should return this"))
from bricknil.bleak_interface import Bleak
ble = Bleak()
# Run curio in a thread
async def dummy(): pass
async def start_curio():
system = await spawn(bricknil.bricknil._run_all(ble, dummy))
while len(ble.devices) < 1 or not ble.devices[0].notify:
await sleep(0.01)
await stop_evt.set()
print("sending quit")
await ble.in_queue.put( ('quit', ''))
#await system.join()
print('system joined')
def start_thread():
kernel.run(start_curio)
t = threading.Thread(target=start_thread)
t.start()
print('started thread for curio')
ble.run()
t.join()