Python in the getopt module,
This module is designed to handle the command line parameters.
function getopt (args, shortopts, longopts = [])
Parameter args is generally sys.argv[1:]
Shortopts short Format (-)
Longopts long Format (--)
Try
Options,args = Getopt.getopt (sys.argv[1:], "HP:I:", ["Help", "ip=", "port="])
Except Getopt. Getopterror:
Sys.exit ()
For Name,value in Options:
If name in ("-H", "--help"):
Usage ()
If name in ("-I", "--ip"):
print ' IP is----', value
If name in ("-P", "--port")
print ' port is----', value
Python test.py-i 127.0.0.1-p 80 55 66
"Hp:i:"
Short format---h is not followed by a colon: indicates that there is no parameter followed, p: and I: a colon after it indicates that a parameter is required later
["Help", "ip=", "port="]
Long format---Help is not followed by an equal sign =, which means that no parameters are followed, the other three have =, indicating that the parameters are required later
Return value options is a list of meta-ancestors, each of which is the parsed format information, such as ['-I ', ' 127.0.0.1 '), ('-P ', ' 80 ')];
Args is a list that contains parameters that do not have '-' or '-', such as: [' 55 ', ' 66 ']
Note: When defining command-line arguments, define parameters with a '-' option, and then define parameters without '-'
Besides, the use of Linux under Getopt
#include <unistd.h>
int getopt (int argc,char * CONST argv[],const char * optstring);
A:b:cd::e ", this is an option string. corresponding to the command line is-A,-B,-C,-D,-E. What is a colon? A colon indicates a parameter, a colon indicates that the option must be followed by an argument (without parameters), but this parameter can be combined with the option to write, or to be separated by a space, such as-a123 and-a 123 (in the middle of a space) is the argument that 123 is the-a parameter, and two colons indicate that the parameter is optional, That can have parameters, or can have no parameters, but to note that there are parameters, parameters and options can not have a space (there is a blank space will be an error), this and a colon when there is a difference.
#include <unistd.h>
#include <stdio.h>
int main (int argc, char * argv[])
{
int ch;
printf ("\ n");
printf ("optind:%d,opterr:%d\n", Optind,opterr);
printf ("--------------------------\ n");
while (ch = getopt (argc, argv, "Ab:c:de::")))!! =-1)
{
printf ("Optind:%d\n", optind);
Switch (CH)
{
Case ' a ':
printf ("Have option:-a\n\n");
Break
Case ' B ':
printf ("Have option:-b\n");
printf ("The argument of-b is%s\n\n", optarg);
Break
Case ' C ':
printf ("Have option:-c\n");
printf ("The argument of-c is%s\n\n", optarg);
Break
Case ' d ':
printf ("Have option:-d\n");
Break
Case ' E ':
printf ("Have option:-e\n");
printf ("The argument of-e is%s\n\n", optarg);
Break
Case '? ':
printf ("Unknown option:%c\n", (char) optopt);
Break
}
}
}
./a.out-a-B 123
Usage of Python getopt