我正在尝试两种方法来阻止无限循环运行:
虽然supervisor_2不会引发中断时,在任何错误,我不能让supervisor_1从得到Task was destroyed but it is pending!。知道为什么吗?
这是代码:
import asyncio
import aioredis
from functools import partial
class Listener:
def __init__(self, redis_conn):
self.redis_conn = redis_conn
async def forever(self, loop_name):
counter = 0
try:
while True:
print('{}: {}'.format(loop_name, counter))
counter += 1
await asyncio.sleep(1)
except asyncio.CancelledError:
print('Task Cancelled')
self.redis_conn.close()
await self.redis_conn.wait_closed()
async def supervisor_1(redis_conn):
redis_conn = await redis_conn
l = Listener(redis_conn)
task = asyncio.ensure_future(
asyncio.gather(l.forever('loop_1'),
l.forever('loop_2')))
await asyncio.sleep(2) …Run Code Online (Sandbox Code Playgroud) async def start(channel):
while True:
m = await client.send_message(channel, "Generating... ")
generator.makeFile()
with open('tmp.png', 'rb') as f:
await client.send_file(channel, f)
await client.delete_message(m)
await asyncio.sleep(2)
Run Code Online (Sandbox Code Playgroud)
我有一个discord bot,每2秒运行一次任务.我尝试使用无限循环,但是脚本崩溃了,Task was destroyed but it is still pending!我已经阅读了有关asyncio的协同程序的内容,但是我发现await它们都没有使用.await例如,通过运行协同程序可以避免此错误吗?
我试图设置一个计时器,它将中断正在运行的进程并在它触发时调用一个协同程序.但是,我不确定实现这一目标的正确方法是什么.我找到了AbstractEventLoop.call_later,以及threading.Timer,但这些似乎都不起作用(或者我使用它们不正确).代码非常基本,看起来像这样:
def set_timer( time ):
self.timer = Timer( 10.0, timeout )
self.timer.start()
#v2
#self.timer = get_event_loop()
#self.timer.call_later( 10.0, timeout )
return
async def timeout():
await some_func()
return
Run Code Online (Sandbox Code Playgroud)
设置非阻塞计时器的正确方法是什么,在几秒钟后调用回调函数?能够取消计时器将是一个奖励,但不是一个要求.我需要的主要事情是:非阻塞并成功调用协同例程.现在它返回一个错误,该对象无法等待(如果我抛出await)或some_func从未等待过,并且预期的输出永远不会发生.
我一直在使用asyncio,但我仍然不熟悉它.我当前的问题是,在尝试等待来自具有asyncio的函数的响应时,等待(while循环)阻止函数发生.以下是总结问题的代码:
import asyncio
response = 0
async def handle(x):
await asyncio.sleep(0.1)
return x
async def run():
global response
for number in range(1, 21):
response = await handle(number)
print(response)
if response == 10:
await wait_for_next(response)
async def wait_for_next(x):
while response == x:
print('waiting',response,x)
await asyncio.sleep(0.5)
print('done')
tasks = [run()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)
wait_for_next应该等待下一个响应,但是while循环阻塞了run()函数.我怎么能阻止这种情况发生?我应该使用loop.run_in_executor,如果是这样,怎么样?
(我可以找到其他几个例子,但它们非常具体,我不明白我们的问题/解决方案是否相同.)
我的程序有一个基于文本的界面(asciimatics 模块),它使用 asyncio 和 discord.py 模块,偶尔当我的 wifi 适配器出现故障时,我会收到如下异常:
Task exception was never retrieved
future: <Task finished coro=<WebSocketCommonProtocol.run() done, defined at /home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py:428> exception=ConnectionResetError(104, 'Connection reset by peer')>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc)
File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 434, in run
msg = yield from self.read_message()
File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 456, in read_message
frame = yield from self.read_data_frame(max_size=self.max_size)
File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 511, in read_data_frame
frame = yield from self.read_frame(max_size)
File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 546, in read_frame
self.reader.readexactly, …Run Code Online (Sandbox Code Playgroud) 我有flask如下服务:
from flask import Flask, request
import json
import time
app = Flask(__name__)
@app.route("/first", methods=["POST"])
def main():
print("Request received")
func1()
return json.dumps({"status": True})
def func1():
time.sleep(100)
print("Print function executed")
if __name__ == "__main__":
app.run("0.0.0.0", 8080)
Run Code Online (Sandbox Code Playgroud)
所以现在当我使用http://localhost:8080/first发出请求时
Request received并等待func1执行然后返回{"status": True}但是现在我不想等待func1完成它的执行,而是它会发送{"status": True}并func1继续它的执行。
从事件线程外部将协程推送到事件线程的pythonic方法是什么?
我有一个 asyncio 应用程序,它使用服务器 fromaiohttp和异步套接字asyncio.open_connection()
我的代码包含来自 PIL 库的一些阻塞调用,例如
Image.save()
Image.resize()
Run Code Online (Sandbox Code Playgroud)
os.path.join()被认为可以?在numpy数组上工作怎么样?tl;dr:如何最大限度地增加可以并行发送的 http 请求数?
我正在使用aiohttp库从多个 url 获取数据。我正在测试它的性能,我观察到在这个过程中的某个地方存在瓶颈,一次运行更多的 url 无济于事。
我正在使用此代码:
import asyncio
import aiohttp
async def fetch(url, session):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'}
try:
async with session.get(
url, headers=headers,
ssl = False,
timeout = aiohttp.ClientTimeout(
total=None,
sock_connect = 10,
sock_read = 10
)
) as response:
content = await response.read()
return (url, 'OK', content)
except Exception as e:
print(e)
return (url, 'ERROR', str(e))
async def run(url_list):
tasks = []
async with …Run Code Online (Sandbox Code Playgroud) 我是一名 Python 初学者,从https://www.youtube.com/watch?v=iG6fr81xHKA&t=269s获取有关 asyncio 强大功能的信息,我尝试使用所示的示例并将其重新调整用途以执行 10 次。这是一个代码片段
def main(x):
print("Hello")
time.sleep(3)
print("World!")
Run Code Online (Sandbox Code Playgroud)
因此,我尝试以异步方式执行此操作,但它不会异步执行。到目前为止,这是我尝试过的。我究竟做错了什么?
import time
import asyncio
async def main(x):
print(f"Starting Task {x}")
await asyncio.sleep(3)
print(f"Finished Task {x}")
async def async_io():
for i in range(10):
await main(i)
if __name__ == "__main__":
start_time = time.perf_counter()
asyncio.run(async_io())
print(f"Took {time.perf_counter() - start_time} secs")
Run Code Online (Sandbox Code Playgroud)
我还尝试在 asyncio 中使用queue_task。
我写了很多依赖于精确的周期性方法调用的代码.我一直在使用Python的futures库将调用提交到运行时的线程池,并在循环中的调用之间休眠:
executor = ThreadPoolExecutor(max_workers=cpu_count())
def remote_call():
# make a synchronous bunch of HTTP requests
def loop():
while True:
# do work here
executor.submit(remote_call)
time.sleep(60*5)
Run Code Online (Sandbox Code Playgroud)
但是,我注意到这个实现在长时间运行后引入了一些漂移(例如,我运行此代码大约10个小时,并注意到大约7秒的漂移).对于我的工作,我需要在确切的秒上运行,毫秒甚至更好.有些人指出我asyncio("火与忘记"python async/await),但我无法在Python 2.7中使用它.
我不是在寻找黑客.我真正想要的是类似于Go time.Tick或Netty的东西HashedWheelTimer.
我正在尝试创建一个简单的监控系统,它会定期检查事物并记录它们。这是我尝试使用的逻辑的简化示例,但我不断收到RuntimeWarning: coroutine 'foo' was never awaited错误消息。
我应该如何从自身重新安排异步方法?
test.py 中的代码:
import asyncio
from datetime import datetime
async def collect_data():
await asyncio.sleep(1)
return {"some_data": 1,}
async def foo(loop):
results = await collect_data()
# Log the results
print("{}: {}".format(datetime.now(), results))
# schedule to run again in X seconds
loop.call_later(5, foo, loop)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(foo(loop))
loop.run_forever()
loop.close()
Run Code Online (Sandbox Code Playgroud)
错误:
pi@raspberrypi [0] $ python test.py
2018-01-03 01:59:22.924871: {'some_data': 1}
/usr/lib/python3.5/asyncio/events.py:126: RuntimeWarning: coroutine 'foo' was never awaited
self._callback(*self._args)
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我想调用task1和task2,但不期望从这些方法返回,这可能吗?
import asyncio
async def say(something, delay):
await asyncio.sleep(delay)
print(something)
loop = asyncio.get_event_loop()
task1 = loop.create_task(say('hi', 1))
task2 = loop.create_task(say('hoi', 2))
loop.run_until_complete(asyncio.gather(task1, task2))
Run Code Online (Sandbox Code Playgroud)
我想处理在 while 循环中进入主队列的某些内容,而无需等待,因为我不需要返回函数,例如伪代码:
import asyncio
async def say(something, delay):
await asyncio.sleep(delay)
print(something)
def main():
while True:
# search for database news
# call say asynchronous, but I do not need any return, I just want you to do anything, independent
time.sleep(1)
Run Code Online (Sandbox Code Playgroud) parallel-processing asynchronous wait python-3.x python-asyncio
python-asyncio ×12
python ×11
python-3.x ×6
asynchronous ×2
discord.py ×2
aiohttp ×1
blocking ×1
flask ×1
go ×1
nonblocking ×1
numpy ×1
python-2.7 ×1
recursion ×1
request ×1
timer ×1
wait ×1