简体   繁体   中英

thread exception occurred in gevent when using python

When I run this python code, but some thread problem occurred. I search the internet,but I don't find the answer.

import urllib2
from time import time
import gevent
import numpy as np

tmp = np.loadtxt('data.txt', dtype=str)
visit_list=tmp[:20]

result_list =[]

def visitUrl(u):
  print 'start %s' %u
  begin = time()
  data = urllib2.urlopen(u).read()
  print len(data)
  print 'end-------- %s' %u
  end = time()
  print ('%s ::begin=%s ::end= %s::end-begin= %s' %(u, begin,end, end-begin))

for i in range(3):
    reqs = []
    begin = time()
    for u in visit_list:
        start = time()
        reqs.append(gevent.spawn(visitUrl, u))
        stop = time()
        print ('%s $$$ %s' %(u, stop-start))
    #reqs = [gevent.spawn(visitUrl, u) for u in visit_list]
    gevent.joinall(reqs)
    end = time()

    print 'ciclie %s=%s' %(i, end - begin)
    result_list.append(end-begin)

the problem:

Exception KeyError: KeyError(4475468392,) in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'> ignored

According to this thread your main loop ends before all threads have done its job.

Just call gevent.shutdown() at the end or increase timeout while calling joinall :

gevent.joinall(reqs, timeout=30)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM