从asyncio.get_event_loop返回结果

时间:2018-05-07 18:50:22

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

我是使用asyncio模块的新手。我有以下代码查询服务以返回ID。如何设置变量以返回< findIntersectingFeatures'功能?

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

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))

1 个答案:

答案 0 :(得分: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)).