-2

What is the best way to process command line arguments into variables? I'm trying to have a python script function such as this:

python file.py 192.168.1.48 8080

If no arguments are entered, it should print the following -

Usage: python file.py (ip address) (port)

So far here is my code. I haven't successfully got arguments to process properly as of yet. Please note this is merely proof of concept. I'm trying to get this working to develop another script. I want the command line arguments to populate the ip and port variables below with the user's input, and validate the input as IP address for ip variable and integer for port if possible. Any help is highly appreciated:

import urllib2
import ssl
ip="192.168.1.48"
port="8080"



ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urllib2.urlopen("https://{0}:{1}".format(ip, port), context=ctx)
CodingNovice
  • 93
  • 1
  • 8

1 Answers1

1

I use getopt. There’s another library called argparse

This code is from the documentation for getopt:

import getopt, sys

def main():
    try:
         opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
       print str(err)  # will print something like "option -a not recognized"
       usage()
       sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
           usage()
           sys.exit()
        elif o in ("-o", "--output"):
           output = a
        else:
            assert False, "unhandled option"
    # ...

    if __name__ == "__main__":
        main()

For your particular case though, you could just import sys and set
ip=sys.arv[1] port= sys.argv[2]

You’d probably want to do some error checking though.

Aaron Paul
  • 117
  • 3
  • 14