2016-06-13 35 views
-1

我試圖追加全球列表變量與新詞在try /除了例外,但嘗試/除了我得到空列表。如何在try/except exception中附加全局列表變量?

list = []        # created empty list with global scope 
    def try_multiple_operations(j): 
      try: 
       jopen = urllib2.urlopen(j) # opened url for parsing content 
       versions = jopen.read() # read and save to variable 
       version = pq(versions)  # filtering content with pyquery 
       ....      # pyquery operations 
       list.append(version) 
      except urllib2.URLError:  # urllib2 exception 
       list.append('0.0') 
      except urllib2.HTTPError:  # urllib2 exception 
       list.append('0.0') 
executor = concurrent.futures.ProcessPoolExecutor(5) 
futures = [executor.submit(try_multiple_operations, j) for j in list] 
concurrent.futures.wait(futures) 
print len(list)      # 0 elements 

最後我得到了空白列表。如何在try/except中添加/附加新結果到全局列表?

+0

? – user2357112

+0

嘗試運行該功能。 – kmad1729

+0

對不起,我更新了代碼。我已經嘗試過但沒有變化。 – user2993877

回答

2

你有幾個問題。首先,list(這確實應該改名,這樣你就不會影內置list功能)是空的,所以

futures = [executor.submit(try_multiple_operations, j) for j in list] 

運行你的函數零點倍。

第二個是ProcessPoolExecutor在另一個進程中運行worker。該工作人員將更新該流程的全球範圍list,而不是主流程中的流程。您應該使用其他池方法之一,如map,並讓您的工作人員返回其結果。

因爲你的代碼是不可運行,我做了一個不同的工作示例

import concurrent.futures 

def try_multiple_operations(j): 
    try: 
     if j % 2: 
      raise ValueError('oops') 
     return '%d even' % j 
    except ValueError: 
     return '%d odd' % j 

executor = concurrent.futures.ProcessPoolExecutor(5) 
my_list = list(executor.map(try_multiple_operations, range(10))) 
print(my_list) 

,做你運行函數的代碼可以改成

def try_multiple_operations(j): 
     try: 
      jopen = urllib2.urlopen(j) # opened url for parsing content 
      versions = jopen.read() # read and save to variable 
      version = pq(versions)  # filtering content with pyquery 
      ....      # pyquery operations 
      return version 
     except urllib2.URLError:  # urllib2 exception 
      return '0.0' 
     except urllib2.HTTPError:  # urllib2 exception 
      return '0.0' 

url_list = [ ...something... ] 
executor = concurrent.futures.ProcessPoolExecutor(5) 
my_list = list(executor.map(try_multiple_operations, url_list) 
print len(my_list)      # 0 elements