python 线程 - 一个问题
我无法找出这段代码中的问题。
class Threader(threading.Thread):
def __init__(self, queue, url, host):
threading.Thread.__init__(self)
self.queue = queue
self.url = url
self.host = host
def run(self):
print self.url # http://www.stackoverflow.com
with contextlib.closing(urllib2.urlopen(self.url)) as u:
source = u.read()
print "hey" # this is not printing!
source = self.con()
doc = Document(source)
self.queue.put((doc, self.host))
当我运行此代码时,print self.url
成功输出 URL,但 print "hey"
不起作用。所以基本上,(我相信)contextlib 中有一些东西阻塞了代码。我也尝试了传统的 urlopen 方法而不使用 contextlib ,但它也不起作用。此外,我尝试了 try
- except
但程序没有引发任何错误。那么这里可能存在什么问题呢?
I can't figure out the problem in this code.
class Threader(threading.Thread):
def __init__(self, queue, url, host):
threading.Thread.__init__(self)
self.queue = queue
self.url = url
self.host = host
def run(self):
print self.url # http://www.stackoverflow.com
with contextlib.closing(urllib2.urlopen(self.url)) as u:
source = u.read()
print "hey" # this is not printing!
source = self.con()
doc = Document(source)
self.queue.put((doc, self.host))
When I run this code, print self.url
succesfully outputs the url but print "hey"
is not working. So basically, (I believe) there is something with contextlib which is blocking the code. I also tried the conventional urlopen
method without using contextlib
, but it doesn't work either. Furthermore, I tried try
- except
but the program doesn't raise any error. So what may be the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码不起作用,我冒昧地对其进行了一些修改(导入,它也不知道 Document 和 self.con),并使其与 python2 兼容(这就是我现在在这里使用的) - 它有效:
编辑:也适用于“with”和 contextlib
Your Code doesn't work, I have taken the liberty to adapt it a bit (imports, also it doesn't know about Document and self.con), and make it compatible with python2 (that's what I use here at the moment) - it works:
EDIT: works also with "with" and contextlib
由于仅使用 urllib 时问题仍然存在,最可能的原因是您尝试打开的 url 没有响应。
您应该尝试
urllib2.urlopen
的timeout
参数Since the problem persists with only using urllib, the most probable cause is that the url you are trying to open does not response.
You should try to
timeout
parameter ofurllib2.urlopen