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 这些都是照着书本上敲得,但是一直报错,搜索了一下也没明白为什么。希望大神能帮忙解答
你这个报错是因为没有加参数呀,就是你8,9,10行指定的参数。
像这样运行:pythontest.py--host127.0.0.1--port9000--filefasdf
书上应该有写呢。
谢谢大神,书上真有写,粗心了版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。