简体   繁体   中英

Python HTTP Respone with Socket and Argparse

I made the code below with a little help from some tutorial online, if you enter a response size, and a correct host and port, everything works fine. But, if you miss a step, it gives you an error. I want to give a custom message to let the user know what they did wrong. Ive looked up how to use 'try' and 'except', but my question is, do I use that from everything in my code? It seems a bit repetitive.

import socket
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-s", "--size", help = "How many bytes you will recive from the HTTP  Response")
parser.add_argument("-p", "--port", help = "The port to which you want to recive a response from")
parser.add_argument("-t", "--host", help = "The host to which you want to recive a response from")

args = parser.parse_args()

size = int(args.size)
port = int(args.port)
host = str(args.host)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

message = ("i")
s.send(message.encode("utf-8"))

data = s.recv(size)
print(data)

If you don't want to do

try:
    size = int(args.size)
except ValueError:
    print("Size is not an integer!")
    sys.exit()

for every argument, you can provide the parser with types for each argument - and it will verify them for you.

parser.add_argument("-s", "--size", help="...", type=int)

Also see this example from the argparse docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM