Python optparse module Usage Analysis, pythonoptparse

Source: Internet
Author: User

Python optparse module Usage Analysis, pythonoptparse

Recently, a problem occurs when you specify parameters to run a specific process. This is similar to the parameters of some commands in Linux, such as ls-a. Why does the-a option respond when it is added. The optparse module Implements similar functions. It transmits command parameters for scripts.

Before using this module, you must first import the OptionParser class in the module, and then create an instance (object) of it ):
Copy codeThe Code is as follows:
From optparse import OptionParser
Parser = OptionParser () # The class parameters can also be defined here.

Then you can add options. Basic Syntax:
Copy codeThe Code is as follows:
Parser. add_option (opt_str ,...,
Attr = value ,...)

Each opt_str can have multiple option strings, such as-f and -- file (the results of ls-a and ls-all in the Linux Command Line are the same). If you define these options, these options are identified when you enter the command line. Otherwise, an error is returned. Opt_str can be defined as follows:
Copy codeThe Code is as follows:
Parser. add_option ("-f", "-- file",...) #-f and -- file are tags of parameters used for calling and will be recognized

After the options are defined, you can call the parse_args () function to obtain the defined options and parameters.
Copy codeThe Code is as follows:
(Options, args) = parser. parse_args () # parse_args can have parameters. If not defined, use the default sys. argv [1:]

Parse_args () returns two values, one being option options (for example,-f) and the other being the args parameter (for example, test.txt)

The four most important attributes of add_option are action, type, dest (destination), and help. Actions are the most basic among the four.

Action parameters (with type and dest introduced ):

The action parameter tells optparse what to do when it encounters an option in the command line. Action has three storage methods: store, store_false, and store_true. If the action value is not specified, the default value is store, which tells optparse to continue reading the next parameter (type) to ensure the correctness of the type, store the value in a variable (dest), that is, the string entered in the command line saves it as the attribute of options, which can be called directly. I am dizzy with a bunch of worships ~~~~, Let's look at an example first!

Copy codeThe Code is as follows:
>>> Parser. add_option ("-f", "-- file", action = "store", type = "string", dest = "filename ")
<Option at 0x2d72f48:-f/-- file>
>>> Args = ["-f", "foo.txt"] # simulate command line input.
>>> (Options, args) = parser. parse_args (args)
>>> Options. filename
'Foo.txt'

Above: When optparselooks at example-F, it will be followed by another example of foo.txt and stored in options. filename (this filename is the dest in add_option). Then the value of dest will be stored as the property of parser. So when parse_argsparameters are used, the value of options.filenameis foo.txt. This is stored as a "string" type. Of course, the type can also be int or float, for example:
Copy codeThe Code is as follows:
Parser. add_option ("-n", type = "int", dest = "num ")

Note: This does not specify a long string option (for example, -- number). This is certainly acceptable, but the option can only be-n when you input the command line, no action is specified, and the default "store" is used ". You can use the simulated command line parameter ["-n22"] (one parameter) again or ["-n 22"] (passed as two parameters ):
Copy codeThe Code is as follows:
>>> Parser. add_option ("-n", type = "int", dest = "num ")
<Option at 0x2d71308:-n>
>>> (Options, args) = parser. parse_args (["-n22"])
>>> Print options. num
22

If the type parameter is not specified, the default type is string, so the simplest method can be written as follows:
Copy codeThe Code is as follows:
Parser. add_option ("-f", dest = "filename ")

The other two values of action are "store_true" and "store_false", which are generally used as a tag. For example, when a program is started, flag is set to True, set flag to False when exiting. After reading the following example, it is completely clear: when Option v is encountered, it sets options. verbose to True. When option q is encountered, it sets options. verbose to False:

Copy codeThe Code is as follows:
>>> From optparse import OptionParser
>>> Parser = OptionParser ()
>>> Parser. add_option ("-v", action = "store_true", dest = "verbose ")
<Option at 0x2ceb888:-v>
>>> Parser. add_option ("-q", action = "store_false", dest = "verbose ")
<Option at 0x2d68e48:-q>
>>> FakeArgs = ['-V', 'Hello']
>>> Options, args = parser. parse_args (fakeArgs)
>>> Options. verbose
True
>>> FakeArgs = ['-Q', 'Bye bye']
>>> Options, args = parser. parse_args (fakeArgs)
>>> Options. verbose
False
# If I write two options v and q at the same time, which one will take as the standard? I tried it and the last one will prevail ~~
>>> FakeArgs = ['-Q', 'Bye bye','-V', 'Hello']
>>> Options, args = parser. parse_args (fakeArgs)
>>> Options. verbose
True

Default parameter:

The default parameter is well understood, that is, when the dest value is not specified, a default value is given, as shown below:
Copy codeThe Code is as follows:
>>> Parser. add_option ("-x", action = "store", dest = "verbose", default = "hahaha ")
<Option at 0x2d77148:-x>
>>> Options, args = parser. parse_args () # No parameters are passed here.
>>> Options. verbose
'Hahahaha'

In this case, the effect of the following two statements is the same (provided that the parameter is not passed to the parse_args () function :)
Copy codeThe Code is as follows:
Parser. add_option ("-v", action = "store_true", dest = "verbose ")
Parser. add_option ("-q", action = "store_false", dest = "verbose", default = True)

Help parameters:

This parameter is used to make the defined "command" more realistic and provides help messages! Haha ~~ The simple usage is as follows:
Copy codeThe Code is as follows:
>>> From optparse import OptionParser
>>> Usage = "myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..]"
>>> Parser = OptionParser (usage) # The usage parameter is added to the class.
>>> OptParser. add_option ("-f", "-- file", action = "store", type = "string", dest = "fileName", help = "no any help ")
<Option at 0x2bdb888:-f/-- file>
>>> FakeArgs = letter '-f', 'file.txt ']
>>> Options, args = parser. parse_args (fakeArgs)
>>> Options. fileName
'File.txt'
>>> Parser. print_help ()
Usage: myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..]

Options:
-H, -- help show this help message and exit # The two rows are automatically generated based on option, which is intelligent ~~
-F FILENAME, -- file = FILENAME
No any help # This is my defined help information (haha, not very friendly ~~)
>>> Parser. print_usage ()
Usage: myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..] # This is the usage information of the class ~~ It's very lifelike?

>>>


The above describes the basic syntax. Here are two examples: one is an example of simulating command line parameters on the Internet, and the other is a "real" example ~~~

Example1:
Copy codeThe Code is as follows:
From optparse import OptionParser
Usage = "myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..]"
OptParser = OptionParser (usage)
OptParser. add_option ("-f", "-- file", action = "store", type = "string", dest = "fileName ")
OoptParser. add_option ("-v", "-- vison", action = "store_false", dest = "verbose", default = 'none ',
Help = "make lots of noise [default]")
FakeArgs = letter '-f', 'file.txt ','-V', 'good luck to you', 'arg2', 'arg']
Options, args = optParser. parse_args (fakeArgs)
Print options. fileName
Print options. verbose
Print options
Print args
Print optParser. print_help ()

The running result is:

Copy codeThe Code is as follows:
File.txt
False
{'Verbose ': False, 'filename': 'file.txt '}
['This is some who', 'arg2', 'arg']
Usage: myprog [-f <filename>] [-s <xyz>] arg1 [, arg2..]
Options:
-H, -- help show this help message and exit
-F FILENAME, -- file = FILENAME
-V, -- vison make lots of noise [default]

Example2:

A simple example is to output the value of n parameter when option n is passed to the script. Otherwise, the default value is given (the script is saved on the E disk ):

Copy codeThe Code is as follows:
From optparse import OptionParser
OptParser = OptionParser ()
OptParser. add_option ("-n", "-- number", action = "store", type = "int", dest = "intNumber ")
OptParser. add_option ("-v", "-- version", action = "store_false", dest = "verbose", default = 'gggggggggggggg', help = "no help ")
Options, args = optParser. parse_args ()
If options. intNumber is not None: # When option n is available, the given parameter value is used.
# Num = options. intNumber
Print options. intNumber, options. verbose

Else:
For I in range (): # If option n is not given, 1 ~ is output by default ~ 4
# Num = I
Print I

Run the following command on cmd:

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.