IndexError:列表索引超出范围

IndexError:列表索引超出范围
#!/usr/bin/env python

import httplib
import sys

#get http server ip
http_server = sys.argv[0]
#create a connection
conn = httplib.HTTPConnection(http_server)

while 1:
    cmd = raw_input('input command (ex. GET index.html): ')
    cmd = cmd.split()

    if cmd[0] == 'exit': #type exit to end it
        break

    #request command to server
    conn.request(cmd[0],cmd[1])

    #get response from server
    rsp = conn.getresponse()

    #print server response and data
    print(rsp.status, rsp.reason)
    data_received = rsp.read()
    print(data_received)

conn.close()

错误

Traceback (most recent call last):
  File "./client1.py", line 19, in <module>
    conn.request(cmd[0],cmd[1])
IndexError: list index out of range

有人能告诉我为什么会出现这个错误吗?有人能修改代码吗?这是用于连接服务器的客户端代码。

我的意见是:GET index.html

但现在我的错误是

File "./client1.py", line 19, in <module>
    conn.request(cmd[0],cmd[1])
  File "/usr/lib/python2.6/httplib.py", line 910, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.6/httplib.py", line 947, in _send_request
    self.endheaders()
  File "/usr/lib/python2.6/httplib.py", line 904, in endheaders
    self._send_output()
  File "/usr/lib/python2.6/httplib.py", line 776, in _send_output
    self.send(msg)
  File "/usr/lib/python2.6/httplib.py", line 735, in send
    self.connect()
  File "/usr/lib/python2.6/httplib.py", line 716, in connect
    self.timeout)
  File "/usr/lib/python2.6/socket.py", line 500, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known

答案1

您对这个问题提供了什么输入?

'input command (ex. GET index.html): '

代码期望您输入类似的命令GET index.html,然后将其拆分为一个名为 cmd 的数组,稍后它尝试访问数组的索引 0 和 1 cmd,并发现没有 cmd[1] 或没有 cmd[0] 和 cmd[1],这可能是因为它收到的输入。

编辑

在回答你的第二个问题时,你需要改变你的路线

http_server = sys.argv[0]

http_server = sys.argv[1]

然后运行你的脚本./scriptname www.google.co.uk

相关内容