2016-11-17 68 views
0

我有任務試圖交易如下:如何使用gevent執行「讀取 - 搜索 - 寫入」任務?

  1. 讀本地文件
  2. 線送線到Web服務查詢
  3. 結果寫入到本地文件

`

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) 

`

我指的是Gevent教程,但無法弄清楚如何將這三個函數放入gevent中。

回答

1

我不知道你的例子與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)]) 

的事情是同時讀取到的搜索和搜索到的寫有依賴性,這是不能夠使用異步的方式來實現這一目標。因此在這個例子中,它可以處理每個函數並一個一個地保存返回值。