C语言及Python命令行参数解析 – getopt

在编写各种命令行程序甚至是GUI程序时,经常需要对命令行参数进行解析处理,以控制程序的执行。当只需要按顺序处理各参数时,可以通过简单地遍历各参数实现。如果要处理稍复杂的命令行参数,则可以使用短选项参数(-a-a arg)与长选项参数(--name--name=arg)。注:短选项-abc-a -b -c等同。

在C语言中,对于短选项参数可以使用getop函数。下面代码摘自http://en.wikipedia.org/wiki/Getopt

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <unistd.h>    /* for getopt */

int main (int argc, char **argv) {
    int c;
    int digit_optind = 0;
    int aopt = 0, bopt = 0;
    char *copt = 0, *dopt = 0;
    while ( (c = getopt(argc, argv, "abc:d:012")) != -1) {
        int this_option_optind = optind ? optind : 1;
        switch (c) {
        case '0':
        case '1':
        case '2':
            if (digit_optind != 0 && digit_optind != this_option_optind)
                printf ("digits occur in two different argv-elements.\n");
            digit_optind = this_option_optind;
            printf ("option %c\n", c);
            break;
        case 'a':
            printf ("option a\n");
            aopt = 1;
            break;
        case 'b':
            printf ("option b\n");
            bopt = 1;
            break;
        case 'c':
            printf ("option c with value '%s'\n", optarg);
            copt = optarg;
            break;
        case 'd':
            printf ("option d with value '%s'\n", optarg);
            dopt = optarg;
            break;
        case '?':
            break;
        default:
            printf ("?? getopt returned character code 0%o ??\n", c);
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }
    exit (0);
}

使用-a -b -c carg -d darg -1参数进行测试,将输出:

option a
option b
option c with value 'carg'
option d with value 'darg'
option 1

在C语言中,对于长选项参数可以使用getop_long函数(同时也支持短选项)。下面代码摘自http://en.wikipedia.org/wiki/Getopt

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>    /* for getopt_long; POSIX standard getopt is in unistd.h */
int main (int argc, char **argv) {
    int c;
    int digit_optind = 0;
    int aopt = 0, bopt = 0;
    char *copt = 0, *dopt = 0;
    static struct option long_options[] = {
        {"add", 1, 0, 0},
        {"append", 0, 0, 0},
        {"delete", 1, 0, 0},
        {"verbose", 0, 0, 0},
        {"create", 1, 0, 'c'},
        {"file", 1, 0, 0},
        {NULL, 0, NULL, 0}
    };
    int option_index = 0;
    while ((c = getopt_long(argc, argv, "abc:d:012",
                            long_options, &option_index)) != -1) {
        int this_option_optind = optind ? optind : 1;
        switch (c) {
        case 0:
            printf ("option %s", long_options[option_index].name);
            if (optarg)
                printf (" with arg %s", optarg);
            printf ("\n");
            break;
        case '0':
        case '1':
        case '2':
            if (digit_optind != 0 && digit_optind != this_option_optind)
                printf ("digits occur in two different argv-elements.\n");
            digit_optind = this_option_optind;
            printf ("option %c\n", c);
            break;
        case 'a':
            printf ("option a\n");
            aopt = 1;
            break;
        case 'b':
            printf ("option b\n");
            bopt = 1;
            break;
        case 'c':
            printf ("option c with value '%s'\n", optarg);
            copt = optarg;
            break;
        case 'd':
            printf ("option d with value '%s'\n", optarg);
            dopt = optarg;
            break;
        case '?':
            break;
        default:
            printf ("?? getopt returned character code 0%o ??\n", c);
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }
    exit (0);
}

使用-a -b --create=carg -d darg -1参数进行测试,也将输出:

option a
option b
option c with value 'carg'
option d with value 'darg'
option 1

在Python中,可以使用getopt模块中的getopt函数,该函数同时支持短选项与长选项。

import sys
import getopt

shortopts = 'abc:d:012'
longopts = ['create=',]

def main():
	optlist, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
	for key, value in optlist:
		print key, value

if __name__ == '__main__':
	main()

使用-a -b -c carg -d darg -1参数进行测试,将输出:

-a
-b
-create carg
-d darg
-1

参考:
1.http://en.wikipedia.org/wiki/Getopt
2.https://docs.python.org/2/library/getopt.html
3.http://linux.die.net/man/3/getopt

C语言及Python命令行参数解析 – getopt》上有1条评论

  1. Pingback引用通告: Shadowsocks源码阅读笔记【1】——语言相关 | 张学程

发表评论

电子邮件地址不会被公开。