我想知道在Python中是否有任何用于异步方法调用的库.如果你可以做类似的事情会很棒
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
doSomethingElse()
if token.finished():
result = token.result()
Run Code Online (Sandbox Code Playgroud)
或者异步调用非异步例程
def longComputation()
<code>
token = asynccall(longComputation())
Run Code Online (Sandbox Code Playgroud)
如果在语言核心中使用更加精细的策略,那就太棒了.这是考虑过吗?
当实现在同步和异步应用程序中都有用的类时,我发现自己在两个用例中维护着几乎相同的代码。
仅作为示例,请考虑:
from time import sleep
import asyncio
class UselessExample:
def __init__(self, delay):
self.delay = delay
async def a_ticker(self, to):
for i in range(to):
yield i
await asyncio.sleep(self.delay)
def ticker(self, to):
for i in range(to):
yield i
sleep(self.delay)
def func(ue):
for value in ue.ticker(5):
print(value)
async def a_func(ue):
async for value in ue.a_ticker(5):
print(value)
def main():
ue = UselessExample(1)
func(ue)
loop = asyncio.get_event_loop()
loop.run_until_complete(a_func(ue))
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
在此示例中,还算不错,串联的ticker方法UselessExample易于维护,但是您可以想象异常处理和更复杂的功能可以迅速增加方法并使之成为问题,即使这两种方法实际上都可以保留下来相同(仅将某些元素替换为它们的异步对应元素)。
假设没有什么实质性差异值得完全实现,那么维护这样的类并避免不必要的重复的最佳方法(也是最Pythonic的)是什么?
背景:我在 Discord 客户端旁边托管了一个 Flask 服务器
Flask 服务器只需要将来自客户端的消息传递给 discord,并将来自 discord 的消息传递给客户端。
我得到的错误,当我打电话loop.run_until_complete(sendMsg(request))
我试图wait_for在sendMsg和wait_for loop.run_until_complete()
我到处找,没有找到任何东西,所以任何帮助将不胜感激。
代码:
import discord
import json
import os
import asyncio
from flask import Flask, request, render_template
from async_timeout import timeout
from threading import Thread
from time import sleep
client = discord.Client()
messages = []
app = Flask(__name__)
def startClient():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client.run('token')
#
# Discord Events
#
@client.event
async def on_ready():
print('Discord Client Ready')
@client.event
async def on_message(message):
global …Run Code Online (Sandbox Code Playgroud) 这似乎是一个常见问题,请参见示例:RuntimeError: This event loop is already running in python
但就我而言,我只启动一次事件循环,至少就我所见。此示例也直接遵循此处的说明:
import asyncio
loop = asyncio.get_event_loop()
async def coroutine():
print("hey")
await asyncio.sleep(1)
print("ho")
return 1
async def main():
tasks = []
for i in range(2):
tasks.append(asyncio.ensure_future(coroutine()))
await asyncio.gather(*tasks)
results = loop.run_until_complete(main())
loop.close()
Run Code Online (Sandbox Code Playgroud)
这将打印一条错误消息,以及协程中的 print() 调用的输出:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-1-f4a74fbfac46> in <module>
16 await asyncio.gather(*tasks)
17
---> 18 results = loop.run_until_complete(asyncio.gather(*tasks))
19 loop.close()
~/anaconda3/envs/keras_dev/lib/python3.6/asyncio/base_events.py in run_until_complete(self, future)
453 future.add_done_callback(_run_until_complete_cb)
454 try:
--> 455 self.run_forever()
456 …Run Code Online (Sandbox Code Playgroud) 我正在运行 Gremlin Python。首先,我按照此处的说明在本地计算机中进行了安装,然后我在此处运行了该网站的代码,但此时出现以下错误:
heading('SubgraphStrategy - just Texas airports')
strategy = SubgraphStrategy(vertices=__.has("region","US-TX"), edges=__.hasLabel('route'))
g2 = g.withStrategies(strategy)
verts = g2.V().count().next()
RuntimeError: Cannot run the event loop while another loop is running
Run Code Online (Sandbox Code Playgroud)
我使用以下代码验证了与 Gremlin Server 的图形数据库的连接
%%graph_notebook_config
{
"host": "localhost",
"port": 8182,
"ssl": false,
"gremlin": {
"traversal_source": "g"
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了一些“RuntimeError:在另一个循环运行时无法运行事件循环”的解决方案,例如 Nest_async ,但后来我收到了不同的错误。
谢谢
python ×5
async-await ×2
asynchronous ×2
coroutine ×1
discord.py ×1
flask ×1
graph ×1
gremlin ×1