sys.argv [1] IndexError:列表索引超出范围

时间:2016-04-19 22:59:40

标签: python python-2.7 command-line httpclient

我正在编写一个Python HTTP客户端。 当我有下面的代码时,我收到来自终端的错误消息"列表索引超出范围"。

from socket import *
import sys

server_host = sys.argv[1]
server_port = sys.argv[2]
filename = sys.argv[3]

host_port = "%s:%s" %(server_host, server_port)
try:
    clientSocket = socket(AF_INET,SOCK_STREAM)
    clientSocket.connect((server_host,int(server_port)))
    header = {
    "first_header" : "GET /%s HTTP/1.1" %(filename),
    "Host": host_port,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US",
    }
    httpHeader = "\r\n".join("%s:%s" %(item,header[item]) for item in     header)
    print httpHeader
    clientSocket.send("%s\r\n\r\n" %(httpHeader))

except IOError:

    sys.exit(1)
final = ""
responseMessage = clientSocket.recv(1024)
while responseMessage:
    final += responseMessage
    responseMssage = clientSocket.recv(1024)

clientSocket.close()
print "final:",final

我通过输入

从命令行运行程序
python ./client.py http://127.0.0.1 7000 HelloWorld.html

有人能告诉我我的代码有什么问题吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

为什么不使用argparse而不是手动处理sys.argv?例如:

import argparse as ap

def argParse():
    parser=ap.ArgumentParser(description='Script to do something')
    parser.add_argument("host", help="web address")
    parser.add_argument("port", help="port to connect on")
    parser.add_argument("filename",help="page to use")
    return parser.parse_args()

然后在主函数调用中:

args=argParse()

然后您可以在代码中使用args.hostargs.portargs.filename,argparse将处理缺少的参数及其类型等。您可以通过添加--来使用可选参数在add_argument()电话中的定义前面。

使用argparse的代码:

from socket import *
import argparse as ap

def argParse():
    parser=ap.ArgumentParser(description='Script to do something')
    parser.add_argument("host", help="web address")
    parser.add_argument("port", type=int, help="port to connect on")
    parser.add_argument("filename",help="page to use")
    return parser.parse_args()

args=argParse()

host_port = "%s:%d" % (args.host, args.port)
try:
    clientSocket = socket(AF_INET,SOCK_STREAM)
    clientSocket.connect((args.host,args.port))
    header = {
    "first_header" : "GET /%s HTTP/1.1" % (args.filename),
    "Host": str(args.port),
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US",
    }
    httpHeader = "\r\n".join("%s:%s" %(item,header[item]) for item in     header)
    print httpHeader
    clientSocket.send("%s\r\n\r\n" %(httpHeader))

except IOError:

    sys.exit(1)
final = ""
responseMessage = clientSocket.recv(1024)
while responseMessage:
    final += responseMessage
    responseMssage = clientSocket.recv(1024)

clientSocket.close()
print "final:",final