我不知道你的例子與gevent有關。無論如何,它仍然可以通過下面的示例代碼進行處理。
import gevent
def read(fin):
for query in fin:
return query
def search(query):
# Send the query to something like Google Search
result = google(query)
return result
def write(fout, result):
fout.write(result)
# read from different files
input_files = ["input1.json", "input2.json" ... ]
# write result into output file
fout = open("output.json", 'wb')
# get queries from input files
queries = []
for input_file in input_files:
with open(input_file, 'rb') as fin:
queries.append(gevent.joinall([gevent.spawn(read, fin)]))
# store results of queries
results = []
for item in [query for query in queries]:
results.append(gevent.joinall([gevent.spawn(search, item[0].value)]))
# save results into output file
for item in [result for result in results]:
gevent.joinall([gevent.spawn(write, fout, item[0].value)])
的事情是同時讀取到的搜索和搜索到的寫有依賴性,這是不能夠使用異步的方式來實現這一目標。因此在這個例子中,它可以處理每個函數並一個一個地保存返回值。