urllib2 urlopen错误:必须是字符串或缓冲区,而不是实例

时间:2015-07-16 18:43:20

标签: python urllib2

我有一个简单的Python脚本,如下所示,它访问PHP脚本。

import urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
url="http://192.168.122.1/info.php/"
datagen, headers = multipart_encode({"file": open("123.txt", 'r')})
request = urllib2.Request(url,datagen,headers)
response = urllib2.urlopen(request)
data = response.read();
print data

但是我收到以下错误:

Traceback (most recent call last):
  File "sample.py", line 8, in <module>
    response = urllib2.urlopen(request)
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 431, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1194, in do_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "/usr/lib/python2.7/httplib.py", line 1048, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 1088, in _send_request
    self.endheaders(body)
  File "/usr/lib/python2.7/httplib.py", line 1044, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python2.7/httplib.py", line 892, in _send_output
    self.send(message_body)
  File "/usr/lib/python2.7/httplib.py", line 864, in send
    self.sock.sendall(data)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
TypeError: must be string or buffer, not instance

这可能是什么原因?或者这是我的PHP脚本的问题。

这是我的PHP脚本

<?php
        echo "Hello";
?>

1 个答案:

答案 0 :(得分:0)

我发现了错误。

https://stackoverflow.com/a/27052062/3460885

从这个问题开始,我必须在开头添加register_openers()。