为什么我会收到此线程错误?
我有这个代码:
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 '---'
但我收到一个错误:
Unhandled exception in thread started by <function workers at 0x0000000002B1FDD8>
有谁知道为什么我收到此错误?
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 exception in thread started by <function workers at 0x0000000002B1FDD8>
Does anyone know why I get this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我运行了您的代码的更简单版本,除了未处理的异常消息之外还看到了堆栈跟踪。它应该可以帮助您定位问题。
您应该考虑一些改进。首先,推荐使用一个高级库
threading
,而不是thread
。其次,您正在使用while 1
循环进行忙碌的等待!使用join()
更可取。通常,在工作代码周围放置异常处理程序也有帮助。例如,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 overthread
. Secondly you are doing a busy wait with thewhile 1
loop! Usejoin()
is lot more preferable. And usually it also help to put a exception handler around your worker code. For example,您在函数中分配给“a”,因此它默认为函数的本地值。
例外情况可能是:
You're assigning to "a" in the function, so it defaults to being local to the function.
The exception may be:
如果只是为了消除错误,请在worker()函数中添加
global a
add
global a
in worker() function if just to eliminate error