开发者社区> 问答> 正文

Traceback (most recent call last):?报错

import sys
import socket
import argparse

def main():
    # setup argument parsing
    parser = argparse.ArgumentParser(description='Socket Error Examples')
    parser.add_argument('--host', action="store", dest="host", required=False)
    parser.add_argument('--port', action="store", dest="port", type=int, required=False)
    parser.add_argument('--file', action="store", dest="file", required=False)
    given_args = parser.parse_args()
    host = given_args.host
    port = given_args.port
    filename = given_args.file

    #First try-except block -- create socket
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, e:
        print "Error creating socket: %s" % e
        sys.exit(1)

    #second try-except block -- connect to given host/post
    try:
        s.connect((host, port))
    except socket.gaierror, e:
        print "Address-related error connecting to sever: %s" % e
        sys.exit(1)
    except socket.error, e:
        print "Connection error: %s" % e
        sys.exit(1)

    #Third try-except block -- sending data
    try:
        s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
    except socket.error, e:
        print "Error sending data: %s" % e
        sys.exit(1)
    
    while 1:
        #Fourth try-except block -- waiting to receive data from remote host
        try:
            buf = s.recv(2048)
        except socket.error, e:
            print "Error receiving data : %s" % e
            sys.exit(1)
        if  not len(buf):
            break
        #write the received data
        sys.stdout.write(buf)
if __name__ == '__main__':
    main()



各位大神好,我刚开始学Python   这些都是照着书本上敲得,但是一直报错,搜索了一下也没明白为什么。希望大神能帮忙解答

展开
收起
爱吃鱼的程序员 2020-06-10 11:23:48 2045 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    你这个报错是因为没有加参数呀,就是你8,9,10行指定的参数。

    像这样运行:pythontest.py--host127.0.0.1--port9000--filefasdf

    书上应该有写呢。

    谢谢大神,书上真有写,粗心了
    2020-06-10 11:24:06
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
阿里云MaxCompute百问百答 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载