python - 在 python 中并行执行 asyncio 函数
问题描述
我是 python 编程的新手,我正在尝试在 python 中学习 asyncio 包以并行执行任务
这是我到目前为止尝试的代码:
import asyncio
import time
from datetime import datetime
import pandas as pd
my_list = [['1320120000000', '48596281','456'], ['1320206400000', '48596281','23259'], ['1320292800000', '50447908','4879']]
#this code is from https://djangostars.com/blog/asynchronous-programming-in-python-asyncio/
async def custom_sleep():
print('SLEEP', datetime.now())
#time.sleep(5)
await asyncio.sleep(2)
async def dataextraction(textdata):
my_list1,my_list2,my_list3=[x[0] for x in textdata],[x[1]for x in
textdata],[x[2] for x in textdata]
await self.custom_sleep()
df2=pd.DataFrame({'firstlist':my_list1,'secondlist':my_list2,'thirdlist':my_list3,'timestamp':datetime.now()})
return df2
start = time.time()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = [
asyncio.ensure_future(der.dataextraction((my_list))),
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
end = time.time()
print("Total time: {}".format(end - start))
#the above code gives output as follows
SLEEP 2018-07-31 17:37:39.916922
firstlist secondlist thirdlist timestamp
0 1320120000000 456 48596281 2018-07-31 17:37:41.920034
1 1320206400000 23259 48596281 2018-07-31 17:37:41.920034
2 1320292800000 4879 50447908 2018-07-31 17:37:41.920034
Total time: 2.0165998935699463
but i think this not correct output,all input data executed at same timestamp,but i am looking for different time stamp values for different input like following example:
firstlist secondlist thirdlist timestamp
0 1320120000000 456 48596281 2018-07-31 17:37:41.760068
1 1320206400000 23259 48596281 2018-07-31 17:37:41.881064
2 1320292800000 4879 50447908 2018-07-31 17:37:41.922369
Total time: 2.0165998935699463
我跨越事件循环概念来完成上述任务,但无法弄清楚如何编码。任何帮助将不胜感激。
解决方案
推荐阅读
- bit-manipulation - 按位补码运算符 (~) 在 C 中的某个点不起作用
- reactjs - 与 React js 集成时,列未使用 Gridjs 显示数据
- c++ - 如何输出存储在另一个变量中的变量
- javascript - 如何防止 Autooptimize 在文章中崩溃我的 JavaScript?
- domain-driven-design - DDD 更正实体的身份
- javascript - `className` 不匹配。服务器:
- mysql - MYSQL TRIGGER AFTER UPDATE 给我这个错误
- python - 将一些特定值添加到 Python 中的另一个列表
- javascript - 如何处理承诺响应?
- php - php,mysql-在一些特殊情况下连接mysql中的三个表