user2993877 user2993877 - 5 months ago 23
Python Question

How to append global list variable in try/except exception in Python?

I'm trying to append global list variable with new words in try/except exceptions, but after try/except I get empty list.

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


At the end I got empty list. How can I add/append new results to global list within try/except?

Answer

In your code, the function try_multiple_operations is never called. Hence no elements are added to the list. After calling it the list will contain the expected elements:

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

try_multiple_operations("http://stackoverflow.com/")
print len(list)                        # 1 element
Comments