为什么我会收到此线程错误?

发布于 2024-11-11 07:14:20 字数 542 浏览 2 评论 0原文

我有这个代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鱼忆七猫命九 2024-11-18 07:14:20

我运行了您的代码的更简单版本,除了未处理的异常消息之外还看到了堆栈跟踪。它应该可以帮助您定位问题。

您应该考虑一些改进。首先,推荐使用一个高级库threading,而不是thread。其次,您正在使用 while 1 循环进行忙碌的等待!使用join() 更可取。通常,在工作代码周围放置异常处理程序也有帮助。例如,

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'

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'
吃素的狼 2024-11-18 07:14:20

您在函数中分配给“a”,因此它默认为函数的本地值。

例外情况可能是:

UnboundLocalError: local variable 'a' referenced before assignment

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
归途 2024-11-18 07:14:20

如果只是为了消除错误,请在worker()函数中添加global a

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文