Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating subcommands with commons-cli

I'm trying to create a simple argument parser using commons-cli and I can't seem to figure out how to create the following options:

java ... com.my.path.to.MyClass producer 
java ... com.my.path.to.MyClass consumer -j 8

The first argument to my program should be either producer or consumer, defining the mode which my program will run in. If it's in consumer mode, I'd like to have a -j argument which defines how many threads to service with.

Here's what I've got so far:

Options options = new Options();
options.addOption("mode", false, "Things.");

HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("startup.sh", options);

When I print out these options, the mode parameter shows up as -mode.

In Python's argparse, I'd just do the following:

parser = argparse.ArgumentParser()
parser.add_argument('mode', choices=('producer', 'consumer'), required=True)
parser.print_help()

This does exactly what I'm looking for. How can I do this in commons-cli?

like image 474
Naftuli Kay Avatar asked May 21 '26 02:05

Naftuli Kay


2 Answers

What I've done for things like this is to have separate Options for each class. In your main, check the first argument to decide which list to pass to the parser. FWIW, I don't consider it "hack" solution.

like image 54
Joe Casadonte Avatar answered May 22 '26 14:05

Joe Casadonte


JCommander is the answer. commons-cli doesn't seem to support these options.

like image 43
Naftuli Kay Avatar answered May 22 '26 15:05

Naftuli Kay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!