Python getopt module

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.