When you use Python for scripting, it is often necessary to invoke the Python script module in the form of a terminal interaction. At this time
Support for providing the underlying command-line parameters in a Python module is essential. So, in Python, how do we implement command-line arguments and parse it, the following is a brief introduction to this.
Python support for command-line argument parsing
Support for command-line argument parsing via two built-in modules in Python: getopt and Optparse
Two built-in support
Module Name |
function Description |
Getopt |
Simple handling of command-line arguments |
Optparse |
The ability to handle complex command-line parameters and easily generate Unix-like help information is more powerful. |
Basic use
Example code:
"""A simple usage example for optparse moduleBy Fat Boy."""from optparse import OptionParser # Import the moduledef main(): opts = parse_command() print("Param filename: " + opts.filename) print("Param Debug: " + str(opts.debug))def parse_command(): parser = OptionParser() # Initialize the OptionParser class # Add commandline parameters format parser.add_option("-f", "--filename", dest="filename", help="Set the output file name") parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch") # Parse the command params (opts, args) = parser.parse_args() return optsif __name__ == "__main__": main()
Test
Enter the following command in the terminal to execute the argv.py.
python argv.py --file=outfile -D
To view the results of the output:
Param filename: outfileParam Debug: True
Introduction to Key methods
"Add_option ()" is the most important method when processing command-line arguments based on the "Optparse" module
Optionparser Initialize Add_option () to define command-line arguments
parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch")
Parameter name |
function |
Description |
Parameter 0 |
First argument, command-line argument short name |
Reference code: "-D" |
Parameter 1 |
Second argument, command-line argument long name |
Reference code: "--debug" |
Action |
Indicates optparse how to handle the store, Store_true, Store_false, Store_const, Append, Count, callback when resolving to a command-line argument |
Default to store |
Dest |
Set the name of the variable that stores the parameter value |
What is stored is the content immediately following the argument |
Type |
Set the data type of the parameter |
The default is string and can also be set: Int/float |
Default |
Set default values for parameters |
|
Help |
To set the Help description text for a parameter |
|
Metavar |
A value to remind the user that the parameter should be entered |
Display as uppercase |
Description
- The value of the action parameter defaults to store, which represents the options object where the command-line arguments are stored.
- Store_true and Store_false are generally used in cases where only the command has no value. Store_true indicates that the variable value defined by the Dest property is set to True when the command appears on the command line. Accordingly, Store_false indicates that the variable value defined by the Dest property is set to False when the command appears on the command line.
Parse_args ()
The method returns the parsed command-line parameter values, as shown in the following:
(opts, args) = parser.parse_args()
Users can pass opts. [dest The specified variable name] to obtain the parsed argument.
For more information, please pay attention to the satellite public number
"Python command-line argument parsing: Optparse module"