2013-10-16 1 views
0

python3 http.client을 사용하여 HTTPConnection을 만들려고합니다. 내가 스크립트 내가 조금 혼란 찾을 수있는 40 (webservice.endheaders()을) 줄을python3 HTTPConnection throw FileNotFoundError

FileNotFoundError: [Errno 2] No such file or directory 

오류 점이다 실행할 때

import http.client 
import base64 
if __name__ == '__main__': 
    username = "xx" # enter your username 
    password = "xxx" # enter your password 
    device_id = "00000000-00000000-00409DFF-FF7660EC" # enter device id of target 
    # Nothing below this line should need to be changed 
    # ------------------------------------------------- 

    # create HTTP basic authentication string, this consists of 
    encodestring = '%s:%s' % (username, password) 
    auth = base64.encodebytes(encodestring.encode('utf-8'))[:-1] 
    # message to send to server 
    message = """<sci_request version="1.0"> 
    <send_message> 
     <targets> 
     <device id="%s"/> 
     </targets> 
     <rci_request version="1.1"> 
      <query_state/> 
     </rci_request> 
    </send_message> 
    </sci_request> 
    """%(device_id) 
    webservice = http.client.HTTPConnection("login.etherios.com ", 80) 
    # to what URL to send the request with a given HTTP method 
    webservice.putrequest("POST", "/ws/sci")  
    # add the authorization string into the HTTP header 
    webservice.putheader("Authorization", "Basic %s" % auth) 
    webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"") 
    webservice.putheader("Content-length", "%d" % len(message)) 
    webservice.endheaders() 
    webservice.send(message) 
    # get the response 
    statuscode, statusmessage, header = webservice.getreply() 
    response_body = webservice.getfile().read() 
    # print the output to standard out 
    print (statuscode, statusmessage) 
    print (response_body) 

오류 메시지 : 여기 내 코드입니다. 아무도 오류 메시지에 빛을 비추 수 있습니까?

In [47]: run import_sensor 
--------------------------------------------------------------------------- 
FileNotFoundError       Traceback (most recent call last) 
/usr/lib/python3/dist-packages/IPython/utils/py3compat.py in execfile(fname, glob, loc) 
    74  def execfile(fname, glob, loc=None): 
    75   loc = loc if (loc is not None) else glob 
---> 76   exec(compile(open(fname, 'rb').read(), fname, 'exec'), glob, loc) 
    77 
    78  # Refactor print statements in doctests. 

/home/markus/python/precirrr-py/precirr/import_sensor.py in <module>() 
    38  webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"") 
    39  webservice.putheader("Content-length", "%d" % len(message)) 
---> 40  webservice.endheaders() 
    41  webservice.send(message) 
    42  # get the response 

/usr/lib/python3.3/http/client.py in endheaders(self, message_body) 
    1055   else: 
    1056    raise CannotSendHeader() 
-> 1057   self._send_output(message_body) 
    1058 
    1059  def request(self, method, url, body=None, headers={}): 

/usr/lib/python3.3/http/client.py in _send_output(self, message_body) 
    900    msg += message_body 
    901    message_body = None 
--> 902   self.send(msg) 
    903   if message_body is not None: 
    904    # message_body was not a string (i.e. it is a file), and 

/usr/lib/python3.3/http/client.py in send(self, data) 
    838   if self.sock is None: 
    839    if self.auto_open: 
--> 840     self.connect() 
    841    else: 
    842     raise NotConnected() 

/usr/lib/python3.3/http/client.py in connect(self) 
    816   """Connect to the host and port specified in __init__.""" 
    817   self.sock = socket.create_connection((self.host,self.port), 
--> 818            self.timeout, self.source_address) 
    819   if self._tunnel_host: 
    820    self._tunnel() 

/usr/lib/python3.3/socket.py in create_connection(address, timeout, source_address) 
    415  host, port = address 
    416  err = None 
--> 417  for res in getaddrinfo(host, port, 0, SOCK_STREAM): 
    418   af, socktype, proto, canonname, sa = res 
    419   sock = None 

FileNotFoundError: [Errno 2] No such file or directory 
+0

실제로 HTTPS 연결 생성자의 호스트 이름 끝에 여분의 공간이 있습니까? 왜냐하면 당신은 '귀뚜라미 (gaierror)'나 비슷한 것을 주어야하기 때문입니다. – abarnert

+0

그리고 그 동안'send'에'TypeError'를 얻을 것입니다; 소켓을 통해'str '을 보낼 수 없다; 그것을 '바이트'로 '인코딩'해야합니다. 그리고'getreply'는 그런 메소드가 없기 때문에 AttributeError를 발생시킬 것입니다. (아마도 당신은'getresponse'을 의미 했을까?) – abarnert

+0

그리고'getfile'에 대해서도 마찬가지입니다. 그러한 방법은 없습니다. 당신은'getresponse'에서 돌아온'HTTPResponse' 객체에 대해'read'를 호출합니다. 이 코드는 어디에서 가져 왔습니까? 튜토리얼에서 복사 한 것이면 더 나은 튜토리얼을 찾을 수 있습니다 ... – abarnert

답변

1

문제는 여기에 있습니다 : : "login.etherios.com "의 끝에 여분의 공간이 유효한 DNS 이름이 아니다 의미

webservice = http.client.HTTPConnection("login.etherios.com ", 80) 

그건

여기에 전체 역 추적입니다. 예를 들면 :

>>> socket.getaddrinfo('login.etherios.com', 80, 0, socket.SOCK_STREAM) 
[(2, 1, 6, '', ('108.166.22.160', 80))] 
>>> socket.getaddrinfo('login.etherios.com ', 80, 0, socket.SOCK_STREAM) 
gaierror: [Errno 8] nodename nor servname provided, or not known 

(. 비우호적 gaierror 멀리 체인까지 친절 -하지만 매우 accurate- FileNotFoundError로 번역되고 있지만, 여기에 너무 중요하지)


그럼, 왜 오류가 끝까지 보입니다. webservice.endheaders()? 파이썬은 여기서 똑똑해 지려고 노력하고 있습니다. 소켓을 즉시 연 다음 한 번에 한 줄씩 데이터를 보내고 그 사이에 소켓을 놓고두면 시스템의 CPU 및 네트워크 리소스가 낭비됩니다 (원격 서버 및/또는 라우터에서 발생) 어쩌면 인터넷에서도 가능합니다. 연결을 열고 즉시 전체 요청을 보내면됩니다 (또는 많은 양의 데이터가있을 때 적어도 헤더의 끝까지). 그래서, 파이썬은 당신을 위해 그것을하려고합니다. 즉, 실제로 사용하려고 시도하기 전까지는 나쁜 정보를 제공한다는 것을 깨닫지 못합니다.

+0

도움을 많이 주셔서 감사합니다. 작은 공간과 같은 영향. 이 문제를 고친 후에 인코딩을 올바르게 설정하고 그에 따라 메서드 이름을 조정하면 마침내 효과가있었습니다. –