Using the Getopt module to handle command-line options

Source: Internet
Author: User
#!/usr/bin/env python #-*-coding:utf8-*-import getopt #函数getopt (args, shortopts, longopts=[]) "" "parameter args is typically s Ys.argv[1:] shortopts Short Form (-) longopts long Format (-) command line input: Python test.py-i 127.0.0.1-p test python test.py--ip=127.0 .0.1--port=80 Test "HP:I:" Short form: H is not followed by a colon to indicate that there are no arguments followed by P: and I: A colon is followed by an argument ["Help", "ip=", "port="] long format: Help is not followed by an equal sign = after the argument is not taken.
The IP and port are followed by =, which means that the next need parameter options is a list containing the progenitor. The format is [(' I ', ' 127.0.0.1 '), (' P ', ' C ']] args is a list that contains parameters that do not have '-' or '-', such as: [' Test ']
    
    Note: When defining command-line arguments, you first define the parameters with the '-' option, and then define no '-' parameters ' "def usage (): print" "" Usage:python opt.py [Option][value] ... -H,--help display Help Info-i,--ip=127.0.0.1 IP address-p,--port=80 port number "" "If __name__== ' __main__ ': TR Y: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
 

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.