命令行參數解析


linux下寫服務端程序免不了用到命令行參數,這里我總結下C語言、bash腳本、pythongo語言中的使用方法,也方便我以后查閱。這里我主要用的是getopt這個函數,首先看看c語言中的定義。

頭文件:#include<unistd.h>

函數定義:int getopt(int argc,char * const argv[ ],const char * optstring);

   extern char *optarg;

   extern int optind, opterr, optopt;

說明:

getopt函數是用來分析命令行參數的,參數argcargv是由main()傳遞的參數個數和內容,參數 optstring為選項字符串, 告知 getopt()可以處理哪個選項以及哪個選項需要參數。

optstring中的指定的內容的意義(例如getopt(argc, argv, "ab:c:de::")

  • 單個字符,表示選項,(如上例中的abcde各為一個選項)

  • 單個字符后接一個冒號:表示該選項后必須跟一個參數。參數緊跟在選項后或者以空格隔開。該參數的指針賦給optarg。(如上例中的b:c:

  • 單個字符后跟兩個冒號,表示該選項后必須跟一個參數。參數必須緊跟在選項后不能以空格隔開。該參數的指針賦給optarg(如上例中的e::)

 

getopt函數所設置的全局變量如下:

  • optarg : 指向當前選項參數(如果有)的指針

  • optind : 再次調用 getopt() 時的下一個 argv 指針的索引。

  • opterr : 是否打印出錯信息,如果不希望getopt()印出錯信息,則只要將全域變量opterr設為0即可。

  • optopt : 最后一個已知選項。

當然,在下面的例子中我也用到了getopt_long這個函數,這個和getopt類似,就不再贅述了。不懂的google下。

1c語言實現

1.1 getopt短命令

代碼如下:

View Code
/*
        File      : getoptShort.c
        Author    : Mike
        E-Mail    : Mike_Zhang@live.com 
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>

extern char *optarg;
extern int opterr;

int main(int argc,char **argv)
{
        int c,index;
        char host[128] = "127.0.0.1";
        int port = 8000;

        opterr = 0;

        while((c=getopt(argc,argv,"h:p:")) != -1)
        {
                switch(c)
                {
                        case 'h':
                                strcpy(host,optarg);
                                break;
                        case 'p':
                                port = atoi(optarg);
                                break;
                        case '?':
                                printf("Usage : \n"
                                "-h host : set ip address\n"
                                "-p port : set port\n"
                                );
                                return 1;
                        default:
                                break;
                }
        }

        printf( "ip   : %s\n"
                "port : %d\n",
                host,port);

        for(index = optind;index < argc;index++)
                printf("Non-option argument %s\n",argv[index]);
        return 0;
}

 運行效果如下:

1.2 getopt長命令

這個要用到getopt_long這個函數。

代碼如下:

View Code
/*
        File      : getoptLong.c
        Author    : Mike
        E-Mail    : Mike_Zhang@live.com 
*/
#include <stdio.h>
#include <string.h>
#include <getopt.h>

extern char *optarg;
extern int opterr;

int main(int argc,char **argv)
{
        int c,index;
        char host[128] = "127.0.0.1";
        int port = 8000;

        struct option opts[] = {
        {"host",required_argument,NULL,'h'},
        {"port",required_argument,NULL,'p'},
        {0,0,0,0}
        };

        opterr = 0;

        while((c=getopt_long(argc,argv,"h:p:",opts,NULL)) != -1)
        {
                switch(c)
                {
                        case 'h':
                                strcpy(host,optarg);
                                break;
                        case 'p':
                                port = atoi(optarg);
                                break;
                        case '?':
                                printf("Usage : \n"
                                "-h host : set ip address\n"
                                "-p port : set port\n"
                                );
                                return 1;
                        default:
                                break;
                }
        }

        printf( "ip   : %s\n"
                "port : %d\n",
                host,port);

        for(index = optind;index < argc;index++)
                printf("Non-option argument %s\n",argv[index]);
        return 0;
}

 運行效果如下:

2Bash腳本實現

bash的和c語言的類似,這里只列舉一個短命令的示例。

代碼如下:

View Code
#! /bin/bash

host="127.0.0.1"
port=8000

if [ $# -gt 0 ] ; then
    while getopts ":h:p:" opt;do
        case $opt in
        h)
            host=$OPTARG
            ;;
        p)
            port=$OPTARG
            ;;
        *)
            echo "Usage :"
            echo "-h arg : set ip address"
            echo "-p arg : set port "
            exit 1;;
        esac
    done
fi

echo "ip   : $host"
echo "port : $port"

3.python實現

python里面的這個函數顯然已經進化了,這個更簡單,還是那個程序的功能,代碼如下:

#! /usr/bin/python

import getopt,sys

if __name__ == "__main__":
    try:
        opts,args = getopt.getopt(sys.argv[1:],"h:p:",["host=","port="])
    except getopt.GetoptError:
        print "Usage :"
        print "-h arg , --host=arg : set ip address"
        print "-p arg , --port=arg : set port"
        sys.exit(1)
    host = "127.0.0.1"
    port = 8000
    for opt,arg in opts:
        if opt in ("-h","--host"):
            host = arg
        if opt in ("-p","--port"):
            port = arg
    print "ip   : ",host
    print "port : ",port

 4.go語言實現

go語言的flag庫似乎更全面,下面是代碼:

package main
import (
        "flag"
        "fmt"
)
var (
        ip = flag.String("host","127.0.0.1","ip address")
        port = flag.String("port","8000","listen port")
)
func main() {
        flag.Parse()
        fmt.Println("ip : ",*ip)
        fmt.Println("port : ",*port)
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM