Last active
October 19, 2015 06:35
-
-
Save everdark/a3d67387fc45bd271b8b to your computer and use it in GitHub Desktop.
command line parser for various language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ParseArg { | |
val usage = "Usage: argparse --s1 v1 --s2 v2 --f opt" | |
def main(args: Array[String]) = { | |
if (args.length == 0) {System.err.println(usage); System.exit(1)} | |
def parseArg(argparsed: Map[Symbol,Any], arglist: List[String]): Option[Map[Symbol,Any]] = { | |
arglist match { | |
case Nil => Some(argparsed) | |
case ("--switch1" | "-s1") :: v1 :: tail => parseArg(argparsed ++ Map('s1 -> v1), tail) | |
case ("--switch2" | "-s2") :: v2 :: tail => parseArg(argparsed ++ Map('s2 -> v2), tail) | |
case ("--flag" | "-f") :: tail => parseArg(argparsed ++ Map('f -> true), tail) | |
case others :: tail if others(0) == '-' => println("Unknown switch: " + others); None | |
case opt :: tail => parseArg(argparsed ++ Map('opt -> opt), arglist.tail) | |
} | |
} | |
val pargs = parseArg(Map('f -> false), args.toList) | |
if (pargs.isDefined) pargs.get.foreach(println) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
def getArgParser(): | |
parser = argparse.ArgumentParser( | |
description="this is the usage string", | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
parser.add_argument("opt1", metavar='opt1', type=str, | |
help="the positional argument.") | |
parser.add_argument("opt2", metavar='opt2', type=str, nargs='?', default="foo", | |
help="positional argument with a default.") | |
parser.add_argument("-a", "--auto", action="store_true", | |
help="the flag argument") | |
parser.add_argument("-n", "--nitem", metavar='N', type=int, action="store", default=10, | |
help="switch of integer argument") | |
return parser | |
def main(): | |
parser = getArgParser() | |
args = parser.parse_args() | |
for k, v in args.__dict__.items(): | |
print k, v | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
argparse.scala
argparse_.py
argparse