aiohttp的入门文档提供了以下客户端示例:
import asyncio
import aiohttp
async def fetch_page(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
assert response.status == 200
return await response.read()
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
content = loop.run_until_complete(
fetch_page(session, 'http://python.org'))
print(content)
Run Code Online (Sandbox Code Playgroud)
他们为Python 3.4用户提供以下注释:
如果您使用的是Python 3.4,请使用@coroutine装饰器替换a yield和async def.
如果我遵循这些说明,我会得到:
import aiohttp
import asyncio
@asyncio.coroutine
def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return (yield from response.text())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
html = loop.run_until_complete(
fetch(session, 'http://python.org'))
print(html)
Run Code Online (Sandbox Code Playgroud)
但是,这不会运行,因为 …
我有一些asyncio代码在Python解释器(CPython 3.6.2)中运行良好.我现在想在一个带有IPython内核的Jupyter笔记本中运行它.
我可以用它来运行它
import asyncio
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)
虽然这似乎工作,它似乎也阻止了笔记本电脑,似乎并没有与笔记本电脑很好玩.
我的理解是Jupyter使用了Tornado,所以我尝试按照Tornado文档中的建议安装Tornado事件循环:
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()
Run Code Online (Sandbox Code Playgroud)
但是,这会产生以下错误:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-1-1139449343fc> in <module>()
1 from tornado.platform.asyncio import AsyncIOMainLoop
----> 2 AsyncIOMainLoop().install()
~\AppData\Local\Continuum\Anaconda3\envs\numismatic\lib\site- packages\tornado\ioloop.py in install(self)
179 `IOLoop` (e.g., :class:`tornado.httpclient.AsyncHTTPClient`).
180 """
--> 181 assert not IOLoop.initialized()
182 IOLoop._instance = self
183
AssertionError:
Run Code Online (Sandbox Code Playgroud)
最后我找到了以下页面:http://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Asynchronous.html
所以我添加了一个包含以下代码的单元格:
import asyncio
from ipykernel.eventloops import register_integration
@register_integration('asyncio')
def loop_asyncio(kernel):
'''Start a kernel with asyncio event loop support.'''
loop = asyncio.get_event_loop() …Run Code Online (Sandbox Code Playgroud) 我在Python 3.5+中读过许多关于asyncio/ async/的博客文章,问题/答案await,很多都是复杂的,我发现最简单的可能是这个.它仍然使用ensure_future,并且为了学习Python中的异步编程,我想看看是否有更简单的例子是可能的(即,执行基本异步/等待示例所需的最小工具是什么).
问题:为了学习Python中的异步编程,是否可以通过仅使用这两个关键字+ + +其他Python代码但没有其他函数来提供一个显示如何async/ await工作的简单示例?asyncio.get_event_loop()run_until_completeasyncio
示例:类似这样的事情:
import asyncio
async def async_foo():
print("async_foo started")
await asyncio.sleep(5)
print("async_foo done")
async def main():
asyncio.ensure_future(async_foo()) # fire and forget async_foo()
print('Do some actions 1')
await asyncio.sleep(5)
print('Do some actions 2')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
但没有ensure_future,仍然演示了await/async的工作原理.
我正在尝试解决以下错误:
\nasyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress\nRun Code Online (Sandbox Code Playgroud)\n这是完整的回溯:
\nTraceback (most recent call last):\n\n File "<string>", line 1, in <module>\n File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/spawn.py", line 116, in spawn_main\n exitcode = _main(fd, parent_sentinel)\n \xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94 4\n \xe2\x94\x82 \xe2\x94\x94 7\n \xe2\x94\x94 <function _main at 0x109c8aca0>\n File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/spawn.py", line 129, in _main\n return self._bootstrap(parent_sentinel)\n \xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94 4\n \xe2\x94\x82 \xe2\x94\x94 <function BaseProcess._bootstrap at 0x109b1f8b0>\n \xe2\x94\x94 <SpawnProcess name='SpawnProcess-4' parent=36604 started>\n File "/Users/ddd/.pyenv/versions/3.8.6/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap\n self.run()\n \xe2\x94\x82 \xe2\x94\x94 <function …Run Code Online (Sandbox Code Playgroud) 我有一个基于tkinter的GUI程序在Python 3.4.1中运行.我在程序中运行了几个线程来从各个URL获取JSON数据.我想添加一些WebSocket功能,以便能够允许程序充当服务器,并允许多个客户端通过WebSocket连接到它并交换其他JSON数据.
我正在尝试使用Autobahn | Python WebSocket服务器进行asyncio.
我首先尝试在GUI程序下的单独线程中运行asyncio事件循环.但是,每次尝试都会产生'AssertionError:线程'Thread-1'中没有当前事件循环.
然后,我尝试使用标准库多处理程序包生成一个进程,该程序包在另一个进程中运行asyncio事件循环.当我尝试这个时,我没有得到任何异常,但WebSocket服务器也没有启动.
甚至可以在另一个Python程序的子进程中运行asyncio事件循环吗?
有没有办法将asyncio事件循环集成到当前多线程/ tkinter程序中?
更新 下面是我尝试运行初始测试的实际代码.
from autobahn.asyncio.websocket import WebSocketServerProtocol
from autobahn.asyncio.websocket import WebSocketServerFactory
import asyncio
from multiprocessing import Process
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
## echo back message verbatim
self.sendMessage(payload, isBinary)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
def start_server():
factory = WebSocketServerFactory("ws://10.241.142.27:6900", debug = False) …Run Code Online (Sandbox Code Playgroud) 我正在使用Python3 Asyncio模块来创建负载平衡应用程序.我有两个繁重的IO任务:
这两个进程将永远运行,彼此独立,不应被另一个进程阻塞.
我不能使用1个事件循环因为它们会阻塞彼此,有没有办法有2个事件循环或者我是否必须使用多线程/处理?
我尝试使用asyncio.new_event_loop(),但还没有设法让它工作.
我一直在阅读python 3中的asyncio模块,更广泛地讲述python中的协同程序,我无法得到使asyncio成为如此优秀工具的原因.我觉得你可以用协同程序做所有事情,你可以通过使用基于多处理模块的任务队列(例如芹菜)来做得更好.是否存在协同程序优于任务队列的用例?
Python 3.4.2
我正在学习asyncio,我用它来不断听IPC总线,而gbulb听dbus.
所以我创建了一个函数listen_to_ipc_channel_layer,它不断地监听IPC通道上的传入消息并将消息传递给message_handler.
我也在听SIGTERM和SIGINT.因此,当我向运行您在底部找到的代码的python进程发送SIGTERM时,脚本应该正常终止.
......我有以下警告:
got signal 15: exit
Task was destroyed but it is pending!
task: <Task pending coro=<listen_to_ipc_channel_layer() running at /opt/mainloop-test.py:23> wait_for=<Future cancelled>>
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
...使用以下代码:
import asyncio
import gbulb
import signal
import asgi_ipc as asgi
def main():
asyncio.async(listen_to_ipc_channel_layer())
loop = asyncio.get_event_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, ask_exit)
# Start listening on the Linux IPC bus for incoming messages
loop.run_forever()
loop.close()
@asyncio.coroutine
def listen_to_ipc_channel_layer():
"""Listens to …Run Code Online (Sandbox Code Playgroud) 以下代码与TypeError: 'Mock' object is not iterablein 失败,ImBeingTested.i_call_other_coroutines因为我已被ImGoingToBeMockedMock对象替换.
如何模仿协同程序?
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_to_run(self):
yield from asyncio.sleep(1)
return "sup"
class ImBeingTested:
def __init__(self, hidude):
self.hidude = hidude
@asyncio.coroutine
def i_call_other_coroutines(self):
return (yield from self.hidude.yeah_im_not_going_to_run())
class TestImBeingTested(unittest.TestCase):
def test_i_call_other_coroutines(self):
mocked = Mock(ImGoingToBeMocked)
ibt = ImBeingTested(mocked)
ret = asyncio.get_event_loop().run_until_complete(ibt.i_call_other_coroutines())
Run Code Online (Sandbox Code Playgroud) 我试图了解如何制作一个等待的对象.文档中的定义指出:
返回迭代器的__await__方法的对象.
在该定义的指导下,我编写了示例代码:
import asyncio
async def produce_list():
num = await Customer()
print(num)
class Customer(object):
def __await__(self):
return iter([1, 2, 3, 4])
loop = asyncio.get_event_loop()
loop.run_until_complete(produce_list())
Run Code Online (Sandbox Code Playgroud)
我期望的流程是:
produce_list().produce_list()放弃执行num = await Customer().Customer()执行并返回一个迭代器.因为返回迭代器中的第一个值.Q1:我不清楚为什么num不成为迭代器本身.这也在做什么send?num = 4协程的执行继续print(num),并打印值4.我得到了什么:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
~/workspace/dashboard/so_question_await.py in <module>()
16
17 loop = asyncio.get_event_loop()
---> 18 loop.run_until_complete(produce_list())
/usr/lib/python3.5/asyncio/base_events.py in run_until_complete(self, future)
464 raise RuntimeError('Event …Run Code Online (Sandbox Code Playgroud) python-asyncio ×10
python ×9
python-3.x ×7
async-await ×3
asynchronous ×3
aiohttp ×1
asyncpg ×1
autobahn ×1
fastapi ×1
jupyter ×1
mocking ×1
python-3.4 ×1
task ×1
tkinter ×1
unit-testing ×1