How to use scopt(https://github.com/scopt/scopt)

In this post, we are going to see how we can use scopt which is a scala library
used to parse the command line options.

The github URL is https://github.com/scopt/scopt

Lot of time, We may need to read and parse the command line arguments. So this simple command line parser used to reduce our burden. Let see how we can use this with a simple example.

Assume that you want to read two parameters from command line, they are input and output directory respectively. You want to throw an error if those parameters are not available.



package com

object ScalaApp extends App {

    case class Arguments(inputDir: String = "",
                         outputDir: String = "")

    val parser = new scopt.OptionParser[Arguments]("Parsing application") {

        opt[String]('i', "inputDir").
            required().valueName("").action((value, arguments) => arguments.copy(inputDir = value))

        opt[String]('o', "outputDir").
            required().valueName("").action((value, arguments) => arguments.copy(outputDir = value))

    }

    def run(arguments: Arguments): Unit = {
        println("Input Dir:" + arguments.inputDir)
        println("Output Dir:" + arguments.outputDir)
    }

    parser.parse(args, Arguments()) match {
        case Some(arguments) => run(arguments)
        case None =>
    }

}


In the above example, I have created a case class Arguments has two fields, input and output directory and I parse the input arguments, if the value is available, then I assign the value to the corresponding field in the case class.

When i run the program with the below command line arguments, then the output will look below,

-i /home/bala/input -o /home/bala/output


com.ScalaApp -i /home/bala/input -o /home/bala/output
Input Dir:/home/bala/input
Output Dir:/home/bala/output

When i run the program without any command line arguments, then it will show the below error as i specified those arguments as required arguments.



com.ScalaApp

Error: Missing option --inputDir
Error: Missing option --outputDir
Usage: test [options]

  -i, --inputDir    
  -o, --outputDir   


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s