开发者

Why do I get this thread error?

开发者 https://www.devze.com 2023-03-09 20:47 出处:网络
I have this code: import urllib2 import thread a = 0 def workers(): while 1: a+=1 silva = urllib2.urlopen(\'http://en.dilandau.eu/download_music/said-the-whale-\'+str(a)+\'.html\')

I have this code:

import urllib2
import thread

a = 0
def workers():

    while 1:

        a+=1
        silva = urllib2.urlopen('http://en.dilandau.eu/download_music/said-the-whale-'+str(a)+'.html')
        si = silva.read()
        if 'var playlist' not in si:
            print a
            break

thread.start_new_thread(workers,())


while 1:
    print '---'

but I get an error:

Unhandled e开发者_高级运维xception in thread started by <function workers at 0x0000000002B1FDD8>

Does anyone know why I get this error?


I ran a simpler version of your code and see a stack trace besides the Unhandled Exception message. It should help you to locate the problem.

There are a few improvement you should consider. First of all there is a high level library threading that is recommended over thread. Secondly you are doing a busy wait with the while 1 loop! Use join() is lot more preferable. And usually it also help to put a exception handler around your worker code. For example,

import threading
import time
import traceback

def worker():
    try:
        for i in range(5):
            print i
            time.sleep(0.5)
        assert 0, 'bad'
    except:
        traceback.print_exc()

t = threading.Thread(target=worker)

t.start()
t.join()

print 'completed'


You're assigning to "a" in the function, so it defaults to being local to the function.

The exception may be:

UnboundLocalError: local variable 'a' referenced before assignment


add global a in worker() function if just to eliminate error

0

精彩评论

暂无评论...
验证码 换一张
取 消