【问题标题】:List Index Out of Range Error : Python列表索引超出范围错误:Python
【发布时间】:2016-01-06 23:38:02
【问题描述】:

我正在从事计算机网络的编程练习:Kurose 和 Ross 的自顶向下方法(第 6 版)

当我运行服务器代码并在浏览器中键入 localhost:1234/www.facebook.com 时,我遇到了 List Index Out of Range 错误。

错误: 收到来自: ('127.0.0.1', 15376) 的连接

消息: 回溯(最近一次通话最后): 文件“Manu.py”,第 17 行,打印 message.split()[1]

IndexError: 列表索引超出范围

代码

from socket import socket
import sys

if len(sys.argv) <= 1:
    print('Usage: "python ProxyServer.py server_ip\n'
          'server_ip: It is the IP Address of the Proxy Server')
    sys.exit(2)

# Create a server socket, bind it to a port and start listening
tcpSerPort = 1234
tcpSerSock = socket(AF_INET, SOCK_STREAM)

# Prepare a server socket
tcpSerSock.bind(('', tcpSerPort))
tcpSerSock.listen(5)

while True:
    # Start receiving data from the client
    print 'Ready to serve...'
    tcpCliSock, addr = tcpSerSock.accept()
    print 'Received a connection from: ', addr
    message = tcpCliSock.recv(1024)

    # Extract the filename from the given message
    print message.split()[1]
    filename = message.split()[1].partition("/")[2]
    fileExist = "false"
    filetouse = "/" + filename

【问题讨论】:

    标签: python proxy network-programming


    【解决方案1】:

    这些是假设某些东西被退回的可能罪魁祸首:

    print message.split()[1]
    filename = message.split()[1].partition("/")[2]
    

    试试:

    m = message.split()
    if m:
        print(m[1])
        filename = m[1].partition("/")[2]
    

    此外,在加入文件时最好不要使用“/”,因为它是特定于平台的。一种更 Pythonic 的方式是使用 join:

    import os
    file_path = os.path.join(directory, filename)
    

    【讨论】:

      【解决方案2】:

      当您从列表中访问没有任何元素的元素时,此行正在创建错误。试试下面的代码,检查是否在消息中获取元素。

      if len(message.split())> 0:
          print message.split()[1]
      

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多