The Optparse module is primarily used to pass command parameters to scripts and to parse command-line arguments with predefined options.
You first need to introduce the Optparser module, then perform the initialization, instantiate a Optionparser object (with or without parameters), and then add options to the command line, for example:
fromOptparseImportOptionparserusage="Show something Usefull-- forExample:how to use the program"Parser= Optionparser (usage)#the contents of the parameter variables will be output as help information.
Parser.add_option ("- F","--file", dest="filename", help="read picture from File", metavar="FILE", action ="Store", type="string") parser.add_option ("- S","--save", dest="Save_mold", help="save image to file or not", default =True) (Options,args)=Parser.parse_args ()Print(Options.filename)Print(Options.save_mold)
The meaning of each parameter:
- Dest: A temporary variable used to hold input, whose value is accessed through the options properties, the stored content is the parameter entered after-F or--file
- Help: Used to generate assistance information
- Default: Defaults to Dest, if the user does not assign a value to dest on the command line argument, the default value is used
- Type: Used to check if the data type of the parameter passed in by the command line parameter is compliant, there are string,int,float and other types
- Action: Used to instruct the program what to do when it encounters command-line arguments, there are three values to choose from: Store,store_false and Store_true, the default value is store
- Store: Read parameters, if the parameter type conforms to the type requirement, pass the parameter value to the DEST variable, which is used as a property of the options.
- Store_true/store_false: Typically used as a tag, set the value of the dest variable to True and false, respectively
- Metavar: Placeholder string, used to output help information, in place of the value of the additional parameters of the current command option, only useful in the help information, notice the difference between its and default
Optparse module usage in python