【问题标题】:Return results from asyncio.get_event_loop从 asyncio.get_event_loop 返回结果
【发布时间】:2018-05-07 18:50:22
【问题描述】:

我是使用 asyncio 模块的新手。我有以下代码查询服务以返回 ID。如何设置变量以从“findIntersectingFeatures”函数返回结果?

另外,如何在 run_in_executor 完成后执行打印语句。他们目前正在第一次迭代后立即打印。

import json, requests, time
import asyncio

startTime = time.clock()

out_json = "UML10kmbuffer.json"

intersections = []

def findIntersectingFeatures(coordinate):

    coordinates = '{"rings":' + str(coordinate) + '}'
    forestCoverURL = 'http://server1.ags.com/server/rest/services/Forest_Cover/MapServer/0/query'
    params = {'f': 'json', 'where': "1=1", 'outFields': '*', 'geometry': coordinates, 'geometryType': 'esriGeometryPolygon', 'returnIdsOnly': 'true'}
    r = requests.post(forestCoverURL, data = params, verify=False)
    response = json.loads(r.content)

    if response['objectIds'] != None:
        intersections.append(response['objectIds'])

    return intersections


with open(out_json, "r") as f_in:
    for line in f_in:
        json_res = json.loads(line)

coordinates = []

# Get features
feat_json = json_res["features"]
for item in feat_json:
    coordinates.append(item["geometry"]["rings"])

loop = asyncio.get_event_loop()

for coordinate in coordinates:
    loop.run_in_executor(None, findIntersectingFeatures, coordinate)


print("Intersecting Features:  " + str(intersections))

endTime = time.clock()
elapsedTime =(endTime - startTime) / 60
print("Elapsed Time: " + str(elapsedTime))

【问题讨论】:

    标签: python-3.x python-requests python-asyncio


    【解决方案1】:

    要使用 asyncio,您不应该只获取事件循环,还必须运行它。您可以使用run_until_complete 运行协程以完成。由于您需要并行运行许多协程,您可以使用asyncio.gather 将它们组合成一个并行任务:

    coroutines = []
    for coordinate in coordinates:
        coroutines.append(loop.run_in_executor(
            None, findIntersectingFeatures, coordinate))
    
    intersections = loop.run_until_complete(asyncio.gather(*coroutines))
    

    另外,如何在run_in_executor 完成后执行打印语句。

    您可以await 调用run_in_executor 并将您的print 放在它后面:

    def find_features(coordinate):
        inter = await loop.run_in_executor(None, findInterestingFeatures, coordinate)
        print('found', inter)
        return inter
    
    # in the for loop, replace coroutines.append(loop.run_in_executor(...))
    # with coroutines.append(find_features(coordinate)).
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2018-11-08
      • 2012-12-19
      • 2019-09-03
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      相关资源
      最近更新 更多