Python getopt module handles command line option instances _python

Source: Internet
Author: User

The Getopt module is used to extract command-line options and parameters, i.e. SYS.ARGV
command-line options make the program more flexible in its parameters. Supports short option mode and long option mode
For example python scriptname.py-f ' hello '--directory-prefix=/home-t--format ' a ' B '

Copy Code code 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 option ', [long option list]]

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

Back to opts and args
OPTs is a tuple of parameter options and their value ('-f ', ' Hello '), ('-t ', ', '), ('--format ', '), ('--directory-prefix ', '/home '))
Args is a command line input other than a useful parameter (' A ', ' B ')

Copy Code code as follows:
# and 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 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 ']

Related Article

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.