getopt demo

SHELL 语法

#!/bin/bash

Usage(){
  echo "Usage: -f <file_name> [-d]\n"
  echo "   -f|--file       the hex file to be decoded.\n"
  echo "   -d|--debug      debug\n"
}

ParseCheckOptions(){
  POSITIONAL=()
  while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
      -h|--help)
        Usage
        exit 0
        shift # past argument
        shift # past value
        ;;
      -f|--file)
        FILE="$2"
        shift # past argument
        shift # past value
        ;;
      -d|--debug)
        DEBUG="$2"
        shift # past argument
        shift # past value
        ;;
      --default)
        DEFAULT=YES
        shift # past argument
        ;;
      *)
        echo unknown option : $1 
        exit -2
        POSITIONAL+=("$1") # save it in an array for later
        shift # past argument
        ;;
    esac
  done

  set -- "${POSITIONAL[@]}" # restore positional parameters

  [ "${FILE}" == "" ] && echo option \-f requires an argument && exit -1
  echo FILE: ${FILE}
  echo DEBUG:${DEBUG}

}

DefaultEnv(){
  FILE=
  DEBUG=0

  #[ ! -d log ] && mkdir log
}

DoActions(){
  echo DoActions
}



Main(){

  startTimeR=`date '+%Y-%m-%d-%H-%M-%S'`
  startTime=`date '+%Y-%m-%d %H:%M:%S'`
  startTime_s=`date +%s`

  DefaultEnv
  ParseCheckOptions $*
  DoActions

  endTime=`date '+%Y-%m-%d %H:%M:%S'`
  endTime_s=`date +%s`

  sumTime=$[ $endTime_s - $startTime_s  ]
  # Convert total seconds into hours, minutes, and seconds
  hours=$(( sumTime / 3600 ))
  minutes=$(( (sumTime % 3600) / 60 ))
  seconds=$(( sumTime % 60 ))
  
  echo "$startTime ---> $endTime"
  echo "Total:$sumTime seconds"
  echo "Converted: $hours hours, $minutes minutes, $seconds seconds"
}


Main $*

C 语法

#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>

static void usage(void)
{
  fprintf(stderr,
      "Usage: -f <file_name> [-d]\n"
      "   -f|--file       the hex file to be decoded.\n"
      "   -d|--debug      debug\n"
      );
}

static const struct option long_opts[] = {
  {"help"    , no_argument       , NULL, 'h'},
  {"file"    , required_argument , NULL, 'f'},
  {"debug"   , required_argument , NULL, 'd'},
  {NULL      , 0                 , NULL, 0  }
};

static int debug = 0;

int main(int argc, char** argv)
{
  const char * short_opt = ":hf:d";
  int hflag = 0;
  int opt = 0;
  int options_index = 0;
  char * file_name;
  opterr = 0;

  if(argc == 1){
    usage();
    return -1;
  }

  //If there are no more option characters, getopt() returns -1.
  while((opt = getopt_long(argc,argv,short_opt,long_opts,&options_index)) != -1) {
    switch(opt)
    {
      case 'h':
        hflag       = 1     ;break;
      case 'f':
        file_name   = optarg;break;
      case 'd':
        debug       = 1     ;break;
      case '?':
        fprintf(stderr,"Error: unknown option '-%c\n'",optopt);
        return -1;
      case ':':
        fprintf(stderr,"Error: option -%c requires an argument\n", optopt);
        return -2;
      default:
        abort();
    }
  }

  if(hflag || argc == 1)
  {
    usage();
    return 0;
  }

  if(!file_name){
    fprintf(stderr,"Error: file name must be specified\n");
    return 1;
  }

  printf("Parameters got: file_name = %s,  debug : %s\n",
            file_name,debug?"YES":"NO");

  return 0;
}

python 语法

#!/usr/bin/python3

import getopt
import sys

input_file = ''
output_file = ''
verbose = False

def parse_options(argv):
    global input_file, output_file, verbose

    try:
        # 解析命令行选项
        opts, args = getopt.getopt(argv, "hi:o:v", ["help", "input=", "output=", "verbose"])

        # 处理选项和参数
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print("使用方法: python script.py -i <input_file> -o <output_file> -v")
                sys.exit()
            elif opt in ("-i", "--input"):
                input_file = arg
            elif opt in ("-o", "--output"):
                output_file = arg
            elif opt in ("-v", "--verbose"):
                verbose = True

    except getopt.GetoptError as err:
        print(str(err))
        print("使用方法: python script.py -i <input_file> -o <output_file> -v")
        sys.exit(2)

def main():
    global input_file, output_file, verbose

    parse_options(sys.argv[1:])  # 解析命令行选项

    # 如果输入文件为空,则输出错误信息并退出
    if not input_file:
        print("错误: 未指定输入文件,请使用 -i 或 --input 选项指定输入文件。")
        print("使用方法: python script.py -i <input_file> -o <output_file> -v")
        sys.exit(2)

    # 打印参数信息
    print(f"输入文件为: {input_file}")
    print(f"输出文件为: {output_file}")
    print(f"是否启用详细模式: {verbose}")

if __name__ == "__main__":
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值