Python getopt Module handles command-line option instances

Source: Internet
Author: User
The Getopt module is used to extract command-line options and parameters, i.e. SYS.ARGV
command-line options make program parameters more flexible. Supports short and long option modes
For example python scriptname.py-f ' hello '--directory-prefix=/home-t--format ' a ' B '
Copy CodeThe code is as follows:


Import getopt, sys
Shortargs = ' F:t '
Longargs = [' directory-prefix= ', ' format ']
opts, args = Getopt.getopt (sys.argv[1:], Shortargs, Longargs)


getopt.getopt ([command line argument list], ' short options ', [long list of options])

Colon after short option name: Indicates that the option must have additional parameters
The equal sign after the long option name = indicates that the option must have additional parameters

Return to opts and args
OPTs is a parameter option and its value tuple ('-f ', ' Hello '), ('-t ', '), ('--format ', '), ('--directory-prefix ', '/home ')
Args is a command-line input (' A ', ' B ') that removes useful arguments

Copy the Code code as follows:

# then traverse opts to get all the command-line options and their corresponding parameters.
For opt, Val in opts:
If opt in ('-f ', '--format '):
Pass
If ....


Use a dictionary to accept command-line input and then transfer the dictionary to make the interface of command-line arguments more robust

# Two examples from python2.5 documentation
Copy the Code code as follows:


>>> Import getopt, sys
>>> arg = '-a-b-C foo-d bar A1 A2 '
>>> optlist, args = Getopt.getopt (sys.argv[1:], ' abc:d: ')
>>> optlist
[('-a ', '), ('-B ', '), ('-C ', ' Foo '), ('-d ', ' Bar ')]
>>> args
[' A1 ', ' A2 ']

>>> arg = '--condition=foo--testing--output-file abc.def-x A1 A2 '
>>> optlist, args = Getopt.getopt (sys.argv[1:], ' x ', [' condition= ', ' output-file= ', ' testing '])
>>> optlist
[('--condition ', ' foo '), ('--testing ', '), ('--output-file ', ' Abc.def '), ('-X ', ')]
>>> args
[' A1 ', ' A2 ']

  • 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.