Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么可以';我无法获取此http_响应的状态代码吗?_Python_Multithreading_Http - Fatal编程技术网

Python 为什么可以';我无法获取此http_响应的状态代码吗?

Python 为什么可以';我无法获取此http_响应的状态代码吗?,python,multithreading,http,Python,Multithreading,Http,为什么会出现此错误: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__a

为什么会出现此错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib/python2.7/urllib2.py", line 435, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
    code, msg, hdrs = response.code, response.msg, response.info()
AttributeError: 'str' object has no attribute 'code'


错误消息的意思是
response
str
,而
str
中没有
code
属性。我怀疑需要解析
response
来提取代码。

在处理程序中,您应该返回
响应

import urllib2
import threading

class MyHandler(urllib2.HTTPHandler):
    def http_response(self, req, response):
        return response

o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=o.open, args=('http://www.google.com/',))
t.start()
t.join()
因为,正如错误所述,http_响应将返回三个值:
code、msg、hdrs

  File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
    code, msg, hdrs = response.code, response.msg, response.info()
但是您正在重写它,以使用
response.getcode()

获取HTTP响应代码 要获取响应代码,您需要处理从线程获取返回结果。讨论中提出了几种实现这一点的方法

以下是如何更改代码以使用队列:

import urllib2
import threading
import Queue


class MyHandler(urllib2.HTTPHandler):
    def http_response(self, req, response):
        return response

que = Queue.Queue()
o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=lambda q, arg1: q.put(o.open(arg1)), args=(que, 'http://www.google.com/'))
t.start()
t.join()
result = que.get()
print result.code

代码打印
200

我只需要返回响应,但现在我不知道如何从线程中获取响应代码。@RickyWilson我想,这不适合同一个问题。但您可以在这里找到关于如何处理线程响应的详细讨论:
import urllib2
import threading
import Queue


class MyHandler(urllib2.HTTPHandler):
    def http_response(self, req, response):
        return response

que = Queue.Queue()
o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=lambda q, arg1: q.put(o.open(arg1)), args=(que, 'http://www.google.com/'))
t.start()
t.join()
result = que.get()
print result.code