Lifove Story

커멘드 라인 옵션 처리를 도와주는 CLI 라이브러리 본문

Lifove Programming

커멘드 라인 옵션 처리를 도와주는 CLI 라이브러리

Lifove 2013. 4. 18. 15:02

연구를 하다가 보면, 여러가지 실험을 돌리기 위한 툴 프로그램을 개발할 때가 많다. 주로 자바로 개발을 하고, 실행가능한 jar파일로 Export하여, 리눅스 서버에서 터미널로 접속해서 커멘드 라인으로 실행할 수 있게 만든다.

그러다 보니, 프로그램 실행시 융통성을 위해 각종 옵션값들을 커멘드라인 파라미터로 처리해야 할 경우가 많은데, 프로그램을 계획없이 짜다보면, 옵션값들이 15개 이상 많이 늘어나는 경우가 있어서, 옵션값의 순서가 헷갈리기도 하고, 옵션들을 잘못 넣는 문제로 실행시 문제가 발생하기도 쉽다.

이런 경우, Apache Software Foundation에서 오픈 소스로 만들어 놓은 Commons CLI라이브러리를 이용하면, 효율적으로 아래와 같은 다양한 종류의 커멘드라인 옵션들을 처리하게 할 수 있다.

Commons CLI supports different types of options:

POSIX like options (ie. tar -zxvf foo.tar.gz)

GNU like long options (ie. du --human-readable --max-depth=1)

Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)

Short options with value attached (ie. gcc -O2 foo.c)

long options with single hyphen (ie. ant -projecthelp)

이 곳(http://commons.apache.org/proper/commons-cli/)에 가면 필요한 모든 정보를 얻을 수 있다.

사용하는 옵션들의 타입마다 구현하는 방식이 조금씩 다른데, 여기서는 "Short options with value attached"방식으로 했다. 제일 간단해 보여서...(복잡한 건 정말 귀찮다;;;)

옵션 만드는 자바 메서드

Options createOptions(){

// create Options object

Options options = new Options();

// add options

options.addOption("sourcefile", true, "Source arff file path");

options.addOption("srclabelname", true, "Source label name");

options.addOption("possrclabel", true, "Positive label of source");

options.addOption("targetfile", true, "Target arff file path");

options.addOption("tgtlabelname", true, "Target label name");

options.addOption("postgtlabel", true, "Positive label of target");

options.addOption("analyzer", true, "Select Co-occurrence analyzer");

return options;

}

만든 옵션을 파싱해주는 메서드

void parseOptions(Options options,String[] args){

CommandLineParser parser = new BasicParser();

try {

CommandLine cmd = parser.parse(options, args);

sourcePath = cmd.getOptionValue("sourcefile");

sourceLabelName = cmd.getOptionValue("srclabelname");

sourceLabelPos = cmd.getOptionValue("possrclabel");

targetPath = cmd.getOptionValue("targetfile");

targetLabelName = cmd.getOptionValue("tgtlabelname");

targetLabelPos = cmd.getOptionValue("postgtlabel");

coOccurrenceAnalyzerOption = cmd.getOptionValue("analyzer");

} catch (ParseException e) {

e.printStackTrace();

}

}

자바 메인 메서드에서 위의 메서드를 호출하는 부분과 옵션값을 스트링으로 받을 수 있는 클래스 변수들이 선언된 코드. 옵션을 만들때, 넣었던 설명을 바탕으로 상황에 따라 도움말 내용을 자동으로 출력할 수도 있다.

String sourcePath;

String sourceLabelName;

String sourceLabelPos;

String targetPath;

String targetLabelName;

String targetLabelPos;

String coOccurrenceAnalyzerOption;


/**

* @param args

*/

public static void main(String[] args) {

new Simulator().run(args);

}

void run(String[] args){

Options options = createOptions();

if(args.length < 7){

// automatically generate the help statement

HelpFormatter formatter = new HelpFormatter();

formatter.printHelp( "CrossPredictionSimulator", options );

}

parseOptions(options, args);

loadSourceAndTargetArffs(sourcePath,targetPath);

}

실제 이클립스에서 위의 선언한데로 옵션값을 넣어준 화면.

혹은, 실행가능한 자바파일(여기서는 Simulator.jar) 만든 다음, 커멘드 라인에서 다음처럼 사용할 수도.

$ java -jar Simulator.jar -sourcefile data/AEEEM/EQ.arff -srclabelname class -possrclabel buggy -targetfile data/ReLink/Apache.arff -tgtlabelname isDefective -postgtlabel TRUE -analyzer regression

아래는 자동으로 도움말이 출력된 모습이다. 위의 소스코드에서는 7개의 옵션들을 커멘드라인에 입력하지 않으면, 도움말이 나오게 했다.

usage: CrossPredictionSimulator

 -analyzer <arg>       Select Co-occurrence analyzer

 -possrclabel <arg>    Positive label of source

 -postgtlabel <arg>    Positive label of target

 -sourcefile <arg>     Source arff file path

 -srclabelname <arg>   Source label name

 -targetfile <arg>     Target arff file path

 -tgtlabelname <arg>   Target label name

반응형