2016-07-26 92 views
0

我有一個函數,它在單個線程中工作。這是一個簡單的例子。基本上我想驗證幾個死鏈接並將結果存儲在字典列表中的每個項目中。對函數使用多處理失敗,字符串索引必須是整數

import requests 
import sys 
import logging 

def main(): 
    urls_to_check = [{'url': 'http://example.com'}, 
        {'url': 'http://example.com'}, 
        {'url': 'http://example.com'}] 
    print check_for_404(urls_to_check) 

def check_for_404(urls_to_check): 
    for item in urls_to_check: 
     r = requests.get(item['url']) 
     item.update({'responseCode': r.status_code}) 
    return urls_to_check 

if __name__ == '__main__': 
    try: 
     main() 
    except: 
     logging.error("Unexpected error:" + str(sys.exc_info())) 

輸出:

[{'url': 'http://example.com', 'responseCode': 200}, {'url': 'http://example.com', 'responseCode': 200}, {'url': 'http://example.com', 'responseCode': 200}] 

如果我實現了多,這是我理解的是跨多個內核和運行部分分裂的迭代,我很高興與

現在可通過函數迭代...

import requests 
import sys 
import logging 
from multiprocessing import Pool 

def main(): 
    urls_to_check = [{'url': 'http://example.com'}, 
        {'url': 'http://example.com'}, 
        {'url': 'http://example.com'}] 
    p = Pool(5) 
    print p.map(check_for_404, urls_to_check) 

def check_for_404(urls_to_check): 
    for item in urls_to_check: 
     r = requests.get(item['url']) 
     item.update({'responseCode': r.status_code}) 
    return urls_to_check 

if __name__ == '__main__': 
    try: 
     main() 
    except: 
     logging.error("Unexpected error:" + str(sys.exc_info())) 

我收到錯誤TypeError('string indices must be integers, not str',), <traceback object at 0x10ad6c128>)

如何實現多處理,以便我可以更快地處理一長串url?

這是我在看教程: https://docs.python.org/2/library/multiprocessing.html

+1

請出示完整的錯誤消息和完整回溯。 – BrenBarn

+0

全部完成。對不起 –

回答

2

你需要改變你的「檢查404的」函數接受單個URL,而不是一個列表; map函數傳入一個列表中的元素在時間(到池中的獨立子過程),然後重新組裝起來,放回表底:

def check_for_404(item): 
    r = requests.get(item['url']) 
    item.update({'responseCode': r.status_code}) 
    return item 
+0

這太酷了。謝謝您的幫助。 –

+0

多處理器調用函數時是否可以使用其他參數?例如'def check_for_404(item,some_other_string_i_may_want_to_use):' –

+0

我認爲最簡單的方法是將所有參數包含在字典中,例如。 '{'url':'example.com','other_string':'blabla'}',並且讓你的功能將它們拉出來 – maxymoo

相關問題