有时需要发生一些非关键的异步操作,但我不想等待它完成.在Tornado的协程实现中,您可以通过简单地省略yield关键字来"触发并忘记"异步功能.
我一直试图弄清楚如何使用Python 3.5中发布的新async/ await语法来"解雇" .例如,简化的代码段:
async def async_foo():
print("Do some stuff asynchronously here...")
def bar():
async_foo() # fire and forget "async_foo()"
bar()
Run Code Online (Sandbox Code Playgroud)
但是会发生什么,bar()从不执行,而是我们得到运行时警告:
RuntimeWarning: coroutine 'async_foo' was never awaited
async_foo() # fire and forget "async_foo()"
Run Code Online (Sandbox Code Playgroud) 我对某些asyncio功能感到有些困惑.我看到有BaseEventLoop.create_task(coro)安排合作例程的功能.文档create_task说它是一个新函数和兼容性,我们应该asyncio.async(coro)通过再次引用docs来看到它是一个别名,asyncio.ensure_future(coro)它再次调度一个协同例程的执行.
与此同时,我一直在Task(coro)用于调度协同例程执行,而且似乎也工作得很好.那么,这些之间的区别是什么?
C#程序员试图学习一些Python。我正在尝试运行CPU密集型计算,同时让IO绑定的异步方法在后台悄悄切换。在C#中,我通常会设置等待的时间,然后启动CPU密集型代码,然后等待IO任务,然后合并结果。
这是我在C#中的做法
static async Task DoStuff() {
var ioBoundTask = DoIoBoundWorkAsync();
int cpuBoundResult = DoCpuIntensizeCalc();
int ioBoundResult = await ioBoundTask.ConfigureAwait(false);
Console.WriteLine($"The result is {cpuBoundResult + ioBoundResult}");
}
static async Task<int> DoIoBoundWorkAsync() {
Console.WriteLine("Make API call...");
await Task.Delay(2500).ConfigureAwait(false); // non-blocking async call
Console.WriteLine("Data back.");
return 1;
}
static int DoCpuIntensizeCalc() {
Console.WriteLine("Do smart calc...");
Thread.Sleep(2000); // blocking call. e.g. a spinning loop
Console.WriteLine("Calc finished.");
return 2;
}
Run Code Online (Sandbox Code Playgroud)
这是python中的等效代码
static async Task DoStuff() {
var ioBoundTask = DoIoBoundWorkAsync();
int cpuBoundResult = DoCpuIntensizeCalc(); …Run Code Online (Sandbox Code Playgroud) 从事件线程外部将协程推送到事件线程的pythonic方法是什么?
我已将 django.channels 添加到 django 项目中,以支持长时间运行的进程,这些进程通过 websockets 通知用户进度。
除了长时间运行的进程的实现似乎没有异步响应之外,一切似乎都运行良好。
为了进行测试,我创建了一个AsyncConsumer识别“run”和“isBusy”两种类型的消息。
“运行”消息处理程序设置“忙标志”,发回“进程正在运行”消息,异步等待20 秒重置“忙标志”,然后发回“进程完成消息”
“isBusy”消息返回带有忙标志状态的消息。
我的期望是,如果我发送一条运行消息,我将立即收到一条“进程正在运行”消息,20 秒后我将收到一条“进程完成”消息。这按预期工作。
我还希望如果我发送“isBusy”消息,我将立即收到带有标志状态的响应。
观察到的行为如下:
下面是 Channel 监听器的实现:
class BackgroundConsoleConsumer(AsyncConsumer):
def __init__(self, scope):
super().__init__(scope)
self.busy = False
async def run(self, message):
print("run got message", message)
self.busy = True
await self.channel_layer.group_send('consoleChannel',{
"type":"consoleResponse",
"text":"running please wait"
})
await asyncio.sleep(20)
self.busy = False
await self.channel_layer.group_send('consoleChannel',{
"type":"consoleResponse",
"text": "finished running"
})
async def isBusy(self,message):
print('isBusy got message', message)
await self.channel_layer.group_send('consoleChannel',{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习在Python中使用asyncio优化脚本。我的示例返回coroutine was never awaited警告,您可以帮助您理解并找到解决方法吗?
import time
import datetime
import random
import asyncio
import aiohttp
import requests
def requete_bloquante(num):
print(f'Get {num}')
uid = requests.get("https://httpbin.org/uuid").json()['uuid']
print(f"Res {num}: {uid}")
def faire_toutes_les_requetes():
for x in range(10):
requete_bloquante(x)
print("Bloquant : ")
start = datetime.datetime.now()
faire_toutes_les_requetes()
exec_time = (datetime.datetime.now() - start).seconds
print(f"Pour faire 10 requêtes, ça prend {exec_time}s\n")
async def requete_sans_bloquer(num, session):
print(f'Get {num}')
async with session.get("https://httpbin.org/uuid") as response:
uid = (await response.json()['uuid'])
print(f"Res {num}: {uid}")
async def faire_toutes_les_requetes_sans_bloquer():
loop = asyncio.get_event_loop()
with aiohttp.ClientSession() …Run Code Online (Sandbox Code Playgroud)