LoginSignup
7
5

More than 5 years have passed since last update.

NDesk.Options を使ってコマンドライン解析を楽にする

Last updated at Posted at 2012-08-18

アプリケーションを作る際に、コマンドライン解析、地味に面倒くさいですよね。
NDesk.Options を使えば、比較的楽に処理することができます。

NDesk.Options のダウンロード

こちらのサイトから最新のZIPファイルを取得し、適当な場所に解凍する。

自分のプロジェクトへの組み込み

  1. 新規プロジェクトを作成
  2. NDesk.Options.dll への参照を追加(ローカルコピー=ON)
  3. あとは、以下のソースコードを参考に。
    • using NDesk.Options; して、
    • OptionSet を定義して、
    • Parse() !!

ソースコード

Program.cs
using System;
using System.Collections.Generic;

using NDesk.Options;

/// <summary>
/// NDesk.Options によるコマンドラインオプション解析のサンプル
/// </summary>
namespace SampleNdeskOptions
{
    class Program
    {
        public static void Main(string[] args)
        {
            bool verbose = false;
            bool recursive = false;
            string output_dir = "";

            List<string> extraCommandLineArgs = new List<string>();

            // コマンドラインオプションの定義
            var p = new OptionSet()
                .Add ("v|version",    dummy => { ShowHelp(); Environment.Exit(0); } )
                .Add ("?|h|help",     dummy => { ShowHelp(); Environment.Exit(0); } )
                .Add ("verbose",          v => { if(v!=null) verbose = true; }      )
                .Add ("o=|output_dir=", dir => { if(dir!=null) output_dir = dir; }  )
                .Add ("r|recursive",      r => { if(r!=null) recursive = true; }    )
                ;

            // 解析
            try {
                // extraCommandLineArgs には、上記オプションを取り除いた残りの引数が入る
                extraCommandLineArgs = p.Parse(Environment.GetCommandLineArgs());
            }
            catch(Exception ex){
                Console.WriteLine(ex.Message);
                Environment.Exit(0);
            }

            // 解析結果の表示
            Console.WriteLine(String.Format("verbose={0}",verbose.ToString()));
            Console.WriteLine(String.Format("recursive={0}",recursive.ToString()));
            Console.WriteLine(String.Format("output_dir={0}",output_dir));

            int index = 0;
            foreach (var arg in extraCommandLineArgs) {
                Console.WriteLine(String.Format("arg[{0}]={1}",index,arg));
                index++;
            }
        }

        /// <summary>
        /// ヘルプの表示
        /// </summary>
        public static void ShowHelp()
        {
            Console.WriteLine("This is help message.");
        }

    }
}

実行結果

>SampleNdesk-options.exe -r
verbose=False
recursive=True
output_dir=
arg[0]=SampleNdesk-options.exe

>SampleNdesk-options.exe
verbose=False
recursive=False
output_dir=
arg[0]=SampleNdesk-options.exe

>SampleNdesk-options.exe file1 file2
verbose=False
recursive=False
output_dir=
arg[0]=SampleNdesk-options.exe
arg[1]=file1
arg[2]=file2

>SampleNdesk-options.exe file1 --verbose file2
verbose=True
recursive=False
output_dir=
arg[0]=SampleNdesk-options.exe
arg[1]=file1
arg[2]=file2

>SampleNdesk-options.exe file1 -r file2
verbose=False
recursive=True
output_dir=
arg[0]=SampleNdesk-options.exe
arg[1]=file1
arg[2]=file2

>SampleNdesk-options.exe file1 --recursive file2
verbose=False
recursive=True
output_dir=
arg[0]=SampleNdesk-options.exe
arg[1]=file1
arg[2]=file2

>SampleNdesk-options.exe file1 -recursive file2
verbose=False
recursive=True
output_dir=
arg[0]=SampleNdesk-options.exe
arg[1]=file1
arg[2]=file2

>SampleNdesk-options.exe -o c:\temp
verbose=False
recursive=False
output_dir=c:\temp
arg[0]=SampleNdesk-options.exe

>SampleNdesk-options.exe -o=c:\temp
verbose=False
recursive=False
output_dir=c:\temp
arg[0]=SampleNdesk-options.exe

>SampleNdesk-options.exe --output_dir=c:\temp
verbose=False
recursive=False
output_dir=c:\temp
arg[0]=SampleNdesk-options.exe

あとは、Ruby の Thor みたいにヘルプメッセージも自動で作成してくれる仕組みがあれば最高なんですけどねー。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5