[英]Python cancel async function
我正在尝试做这样的事情
def noAsyncPrint(c):
sleep(random.uniform(1,10))
print(c)
chars = ['a','b','c']
for c in chars:
noAsyncPrint(c)
得到这个输出
a, b, c
我如何获得一些随机订单? 谢谢你 :)
编辑清楚我的例子
**这只是一个清晰的基本例子,它应该是做几件事后的随机api请求**
您可以使用multiprocessing.pool 中的ThreadPool
:
from multiprocessing.pool import ThreadPool
from time import sleep
import random
def noAsyncPrint(c):
sleep(random.uniform(1,10))
print(c)
chars = ['a','b','c']
with ThreadPool(3) as p:
p.map(noAsyncPrint, chars)
输出:
a
c
b
输出是随机的,可以是任意组合
在上面的代码中,您使用了 3 个线程,它们将以异步方式执行您的函数noAsyncPrint
,因此您的输出是随机的
您可能想要使用asyncio 库。 查看本指南以获得一个很好的演练。 以下示例使用gather()
函数以并发方式调度async_print()
。 我还添加了带时间戳的日志记录以使执行顺序可见:
import logging
import random
import asyncio
lgr = logging.getLogger('main')
async def async_print(c):
tau = round(random.uniform(1,10))
lgr.debug(f"async_print('%s'): - sleeping of %g sec ...", c, tau)
await asyncio.sleep(tau)
lgr.debug(f"async_print('%s'): ... done sleeping.", c)
print(c)
async def main():
chars = ['a','b','c']
lgr.info("Creating futures... ")
list_of_futures = [async_print(c_) for c_ in chars]
lgr.debug("Calling futures concurrently ... ")
await asyncio.gather(*list_of_futures)
lgr.info(" ... done.")
logging.basicConfig(level=logging.DEBUG, datefmt="%H:%M:%S",
format='%(asctime)s %(name)s[%(lineno)s] %(levelname)s %(message)s')
asyncio.run(main())
输出如下所示:
15:17:56 asyncio[59] DEBUG Using selector: EpollSelector
15:17:56 main[17] INFO Calling futures ...
15:17:56 main[19] DEBUG Waiting for completion ...
15:17:56 main[9] DEBUG async_print('a'): - sleeping of 9 sec ...
15:17:56 main[9] DEBUG async_print('b'): - sleeping of 9 sec ...
15:17:56 main[9] DEBUG async_print('c'): - sleeping of 1 sec ...
15:17:57 main[11] DEBUG async_print('c'): ... done sleeping.
c
a
b
15:18:05 main[11] DEBUG async_print('a'): ... done sleeping.
15:18:05 main[11] DEBUG async_print('b'): ... done sleeping.
15:18:05 main[21] INFO ... done.
请注意, print()
函数并不总是立即显示输出。 日志功能在这方面表现得更好。
在 numpy 库中,有一个随机顺序函数,称为np.random.suffle()
import numpy as np # import the numpy lybrary
def noAsyncPrint(c):
sleep(random.uniform(1,10))
print(c)
chars = np.array(['a','b','c']) #make it a np array
random_chars = np.random.suffle(chars) # shuffle it!
for c in random_chars:
noAsyncPrint(c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.