Action: Handling command-line arguments
Functions: Getopt (args, shortopts, longopts = [])
Parameter args is generally sys.argv[1:] shortopts short Format (-) longopts long Format (--)
Example:
Script File test.py content
Import getopt
Import Sys
def usage ():
Print (' usage:\n python test.py-i 127.0.0.1-p 80 55 66 ')
Try
Options,args = Getopt.getopt (sys.argv[1:], "HP:I:", ["Help", "ip=", "port="])
Except Getopt. Getopterror:
Sys.exit ()
For Name,value in Options:
If name in ("-H", "--help"):
Usage ()
If name in ("-I", "--ip"):
print ' IP is----', value
If name in ("-P", "--port"):
print ' port is----', value
Execute script
================================
1. Command: Python test.py-h
Output: Usage:python test.py-i 127.0.0.1-p 80 55 66
2. Command: Python test.py-i 127.0.0.1-p 80 55 66
Output: IP is----127.0.0.1 port is----80
3. Command: Python test.py--ip=127.0.0.1--port=80 55 66
Output: IP is----127.0.0.1 port is----80
Command explanation:
The command 1:shortopts (short form) has no colon after H: Indicates that no arguments are followed
Command 2:shortopts (short format) i,p followed by a colon, followed by 127.0.0.1 and 80 respectively for the-I and-p parameters
Command 3:longopts (long format) Ip,port followed by an equals sign, followed by 127.0.0.1 and 80 respectively for--IP and--port parameters--Same as command 2, except for parameter formats
Python getopt module