我有asyncio.Task一段时间需要取消。在取消之前,任务需要做一些清理工作。根据文档,我应该只能在协程中调用 task.cancel 或asyncio.wait_for(coroutine, delay)拦截 an asyncio.TimeoutError,但以下示例不起作用。我尝试过拦截其他错误并调用task.cancel,但都没有成功。我是否误解了取消任务的工作原理?
@asyncio.coroutine
def toTimeout():
try:
i = 0
while True:
print("iteration ", i, "......"); i += 1
yield from asyncio.sleep(1)
except asyncio.TimeoutError:
print("timed out")
def main():
#... do some stuff
yield from asyncio.wait_for(toTimeout(), 10)
#... do some more stuff
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud) 我正在使用asyncioPython 模块,但我不知道我的简单代码有什么问题。它不会异步执行任务。
#!/usr/bin/env python3
import asyncio
import string
async def print_num():
for x in range(0, 10):
print('Number: {}'.format(x))
await asyncio.sleep(1)
print('print_num is finished!')
async def print_alp():
my_list = string.ascii_uppercase
for x in my_list:
print('Letter: {}'.format(x))
await asyncio.sleep(1)
print('print_alp is finished!')
async def msg(my_msg):
print(my_msg)
await asyncio.sleep(1)
async def main():
await msg('Hello World!')
await print_alp()
await msg('Hello Again!')
await print_num()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Run Code Online (Sandbox Code Playgroud)
这是调用脚本时的输出:
Hello World!
Letter: A
Letter: B
Letter: C
Letter: …Run Code Online (Sandbox Code Playgroud) 我昨天刚刚学习了 python 3.5 的异步。
这就是我今天想要完成的任务。
import asyncio
import time
import requests
async def foo():
"""Some Long Running Taks"""
requests.get("http://stackoverflow.com/questions/41301031/asyncio-on-long-running-task")
print("foo")
async def bar():
"""Some Quick Task"""
print("bar")
while True:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(foo(), bar()))
loop.close()
time.sleep(2)
#Expected output
"""
>>>bar
>>>bar
>>>bar
>>>bar
>>>bar
>>>foo
and so on
"""
Run Code Online (Sandbox Code Playgroud)
使用 python async/await 可以吗?
我认为它ayncio的使用coroutine与线程无关,因为coroutine它是在程序调度程序下运行的一种“线程”,所以每个进程应该只有1个线程运行。但是当我运行使用 python-aiohttp 发出 100 万个请求中的示例时,代码如下所示:
# modified fetch function with semaphore
import random
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
async with session.get(url) as response:
delay = response.headers.get("DELAY")
date = response.headers.get("DATE")
print("{}:{} with delay {}".format(date, response.url, delay))
return await response.read()
async def bound_fetch(sem, url, session):
# Getter function with semaphore.
async with sem:
await fetch(url, session)
async def run(r):
url = "http://localhost:8080/{}"
tasks = []
# create instance of …Run Code Online (Sandbox Code Playgroud) 我有一个由 Cython 封装的 C++ 外部库。这个 C++ 库本身我无法更改。我想将该库组合起来用作Python应用程序的一部分,该应用程序使用asyncio作为其主要过程控制。
Cython 库本质上是使用专有协议进行网络工作。然而,当在 python 中启动库的事件处理程序时,Cython 库会阻塞。我已经达到了可以传递 Python 函数并接收从 C++ 库接收的事件的回调的阶段。如果我在 event_loop.run_in_executor 中运行事件处理程序,我可以解决库在库事件处理程序中挂起应用程序的问题。
我的问题是,我如何才能最好地对此进行建模,以便与与其接口完美契合的 asnycio 一起使用,而不是破解临时解决方案以使用 Cython 库方法?我考虑将其编写为 asyncio.Protocol 和 asyncio.Transport,然后使用 Cython 库作为其底层通信机制。然而,看起来需要付出很大的努力才能使它看起来像一个套接字。是否有更好的方法或抽象来将包装器放在外部库上以使其与 asyncio 一起使用?
import asyncio
import asyncio.subprocess
args="blah blah argument "
create=asyncio.create_subprocess_shell(args,stdout=asyncio.subprocess.PIPE)
proc = await create
output= await proc.stdout.read( )
Run Code Online (Sandbox Code Playgroud)
这是我的服务器代码的一部分,它从客户端获得数千个并行点击。现在我应该如何限制服务器创建的子进程的最大数量来运行参数等等。因为这段代码使用了我 100% 的 CPU。我需要在 smae cpu 上部署其他服务器
我试图同时请求一堆 URL,但 URL 是从列表构建的。目前,我正在循环列表并(我认为)将它们添加到队列中。它肯定比 requests.get 快 10 倍,但是我不确定我是否正确执行,因此可以对其进行优化。我对其进行了分析,发现在并发请求完成后,90% 的时间它仍然处于锁定状态,即开始 -> 10+ 并发请求 -> 锁定 5 秒左右 -> 完成
Unclosed client session此外,此代码最后会生成一条消息。知道为什么吗?很确定这是正确使用上下文管理器。
我已经搜索过但没有找到这个确切的问题
import signal
import sys
import asyncio
import aiohttp
import json
import requests
lists = ['eth', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo']
loop = asyncio.get_event_loop()
client = aiohttp.ClientSession(loop=loop)
async def fetch(client, url):
async with client.get(url) as resp:
assert resp.status == 200
return await resp.text()
async def main(loop=loop, url=None):
async with …Run Code Online (Sandbox Code Playgroud) 我正在做一些测试,我想知道下面的脚本是否异步运行?
# python test.py It took 1.3439464569091797 seconds.
Run Code Online (Sandbox Code Playgroud)
31(站点)x 1.34 = 41.54s - 所以少了几秒,但理论上它应该只需要最长的请求?
# python test.py It took 28.129364728927612 seconds.
Run Code Online (Sandbox Code Playgroud)
也许打开浏览器在这里不是异步的,我应该为此使用执行器?
# cat test.py
import asyncio
import time
from pyppeteer import launch
from urllib.parse import urlparse
WEBSITE_LIST = [
'http://envato.com',
'http://amazon.co.uk',
'http://amazon.com',
'http://facebook.com',
'http://google.com',
'http://google.fr',
'http://google.es',
'http://google.co.uk',
'http://internet.org',
'http://gmail.com',
'http://stackoverflow.com',
'http://github.com',
'http://heroku.com',
'http://djangoproject.com',
'http://rubyonrails.org',
'http://basecamp.com',
'http://trello.com',
'http://yiiframework.com',
'http://shopify.com',
'http://airbnb.com',
'http://instagram.com',
'http://snapchat.com',
'http://youtube.com',
'http://baidu.com',
'http://yahoo.com',
'http://live.com',
'http://linkedin.com',
'http://yandex.ru',
'http://netflix.com',
'http://wordpress.com',
'http://bing.com',
]
start = time.time()
async def fetch(url):
browser …Run Code Online (Sandbox Code Playgroud) 我有一段代码需要很长时间才能执行并且占用 CPU 资源。我想多次运行该块,并希望为此充分利用 CPU 的能力。看了一下就asyncio明白了,它主要是为了异步通信,但也是异步任务的通用工具。
在以下示例中,这time.sleep(y)是我要运行的代码的占位符。在此示例中,每个协同例程都依次执行,执行时间约为 8 秒。
import asyncio
import logging
import time
async def _do_compute_intense_stuff(x, y, logger):
logger.info('Getting it started...')
for i in range(x):
time.sleep(y)
logger.info('Almost done')
return x * y
logging.basicConfig(format='[%(name)s, %(levelname)s]: %(message)s', level='INFO')
logger = logging.getLogger(__name__)
loop = asyncio.get_event_loop()
co_routines = [
asyncio.ensure_future(_do_compute_intense_stuff(2, 1, logger.getChild(str(i)))) for i in range(4)]
logger.info('Made the co-routines')
responses = loop.run_until_complete(asyncio.gather(*co_routines))
logger.info('Loop is done')
print(responses)
Run Code Online (Sandbox Code Playgroud)
当我替换time.sleep(y)它时asyncio.sleep(y),它几乎立即返回。大约await asyncio.sleep(y)需要2秒钟。
有没有办法使用这种方法并行化我的代码,或者我应该使用multiprocessingor threading?我需要将其放入 …
我想为某个项目构建一个自定义服务器,但我不知道和服务器之间有什么区别,什么更好用,以及为什么asyncoreasyncio
python ×10
python-asyncio ×10
aiohttp ×2
asynchronous ×2
python-3.x ×2
asyncore ×1
asyncsocket ×1
cython ×1
pyppeteer ×1
subprocess ×1