我有一个使用asyncio和await模块的python程序.这是我从这里开始的一个示例程序
.
import asyncio
import os
import urllib.request
import await
@asyncio.coroutine
def download_coroutine(url):
"""
A coroutine to download the specified url
"""
request = urllib.request.urlopen(url)
filename = os.path.basename(url)
with open(filename, 'wb') as file_handle:
while True:
chunk = request.read(1024)
if not chunk:
break
file_handle.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
@asyncio.coroutine
def main(urls):
"""
Creates a group of coroutines and waits for them to finish
"""
coroutines = [download_coroutine(url) for url in urls]
completed, …Run Code Online (Sandbox Code Playgroud) 我有一个python程序,正在启动随机数的异步协程。在这段时间内,我的程序可以启动新程序,其中一些程序可以在终止工作后退出。
我想知道是否有可能每分钟报告一次活性协程的数量吗?
谢谢
我们有一种方法来设置线程名称:thread = threading.Thread(name='Very important thread', target=foo)然后%(thread)s:在格式化程序中获取该名称以用于记录目的。可以用这样的方法做asyncio.Task吗?
goroutine大致相当于python的asyncio任务,还有一个额外的功能,即任何CPU绑定的任务都被路由到一个ThreadPoolExecutor而不是被添加到事件循环中(当然,假设我们使用没有GIL的python解释器)?
我失踪的两种方法之间有什么实质性的区别吗?当然,除了并发性是Go的一个组成部分所带来的效率和代码清晰度之外.
据我了解,从协程中的协程产生的结果将线程控制传递给事件循环。
然后,事件循环在其他协程(在其中,从协程产生的协程)之间进行某种调度,并在某个时间点恢复称为yield from的协程。
与将协程包装在ansyncio.wait_for调用中并从后者中产生什么有什么不同?
我正在为我制作的服务器开发一个小的discord bot,但是我遇到了一个问题.每当我尝试运行bot(使用python3.4 lilac.py)时,我都会收到以下错误:
Traceback (most recent call last):
File "lilac.py", line 7, in <module>
@asyncio.coroutine
NameError: name 'asyncio' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0xb61ad470>
Run Code Online (Sandbox Code Playgroud)
我尝试通过安装它python3.4 -m pip install asyncio,即使它说安装成功,我仍然得到错误.这是完整的代码:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='&&', description="Description here")
@bot.event
@asyncio.coroutine
def on_ready():
print('Logged in as')
print(bot.user.name)
Run Code Online (Sandbox Code Playgroud)
有什么我没有正确安装?我是否错误地调用了asyncio?任何帮助表示赞赏,如果需要,我可以提供更多信息.
我是python的新手,并努力理解为什么我的coroutine不工作.
在当前代码中,唯一一个作业正在运行而另一个作业始终处于空闲状态.为什么?
class Worker:
def job1_sync(self):
count = 0
while True:
print('JOB A:', count)
count = count + 1
def job2_sync(self):
count = 0
while True:
print('JOB B:', count)
count = count + 1
async def job1(self):
await self.job1_sync()
async def job2(self):
await self.job2_sync()
worker = Worker()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.gather(worker.job1(), worker.job2()))
Run Code Online (Sandbox Code Playgroud) 我正在尝试同时调用~300个API调用,这样我最多可以在几秒内得到结果.
我的伪代码看起来像这样:
def function_1():
colors = ['yellow', 'green', 'blue', + ~300 other ones]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
res = loop.run_until_complete(get_color_info(colors))
async def get_color_info(colors):
loop = asyncio.get_event_loop()
responses = []
for color in colors:
print("getting color")
url = "https://api.com/{}/".format(color)
data = loop.run_in_executor(None, requests.get, url)
r = await data
responses.append(r.json())
return responses
Run Code Online (Sandbox Code Playgroud)
这样做我getting color每隔一秒左右打印一次,代码需要永远,所以我很确定它们不会同时运行.我究竟做错了什么?
有关更新的问题:
假设我有2个处理生成器函数:
def gen1(): # just for examples,
yield 1 # yields actually carry
yield 2 # different computation weight
yield 3 # in my case
def gen2():
yield 4
yield 5
yield 6
Run Code Online (Sandbox Code Playgroud)
我可以用itertools链接它们
from itertools import chain
mix = chain(gen1(), gen2())
Run Code Online (Sandbox Code Playgroud)
然后我可以用它创建另一个生成器函数对象,
def mix_yield():
for item in mix:
yield item
Run Code Online (Sandbox Code Playgroud)
或者只是如果我只是想next(mix),它就在那里。
我的问题是,我该如何做异步代码中的等效代码?
因为我需要它来:
next迭代器上一页 更新:
经过实验和研究后,我发现aiostream库声明为itertools的异步版本,因此我做了什么:
import asyncio
from aiostream import stream
async def gen1():
await asyncio.sleep(0)
yield 1
await …Run Code Online (Sandbox Code Playgroud) python asynchronous sequence-generators python-3.x python-asyncio
我正在测试aiohttp和asyncio。我希望同一事件循环具有套接字,http服务器,http客户端。
我正在使用以下示例代码:
@routes.get('/')
async def hello(request):
return web.Response(text="Hello, world")
app = web.Application()
app.add_routes(routes)
web.run_app(app)
Run Code Online (Sandbox Code Playgroud)
问题run_app是阻塞。我想将http服务器添加到使用以下命令创建的现有事件循环中:
asyncio.get_event_loop()
Run Code Online (Sandbox Code Playgroud) python-asyncio ×10
python ×7
python-3.x ×4
coroutine ×3
aiohttp ×1
asynchronous ×1
concurrency ×1
discord.py ×1
go ×1
monitoring ×1
python-3.4 ×1
python-3.6 ×1