Skip to content
Remko Popma edited this page Apr 28, 2019 · 35 revisions

Executing Commands

Picocli 4.0 introduced new API to execute commands. Let’s take a quick look at what changed.

Exit Code

Many command line applications return an exit code to signify success or failure. Zero often means success, other than that, conventions differ.

The new execute API returns an int, and applications can use this value to call System.exit if desired.

Older versions of picocli had some exit code support where picocli would call System.exit, but this is now deprecated.

Example Usage

public static void main(String... args) {
  CommandLine cmd = new CommandLine(new App());
  int exitCode = cmd.execute(args);
  System.exit(exitCode);
}

Generating an Exit Code

@Command-annotated classes that implement Callable and @Command-annotated methods can simply return an int or Integer value that will be returned from CommandLine.execute. For example:

@Command(name = "greet")
class Greet implements Callable<Integer> {
  public Integer call() {
    System.out.println("hi");
    return 1;
  }

  @Command
  int shout() {
    System.out.println("HI!");
    return 2;
  }
}

Commands with a user object that implements Runnable can implement the IExitCodeGenerator interface to generate an exit code. For example:

@Command(name = "wave")
class Wave implements Runnable, IExitCodeGenerator {
  public int getExitCode() {
    return 3;
  }
  public void run() {
    System.out.println("wave");
  }
}

The above commands define two top-level commands, greet and wave. The greet command has one subcommand, shout.

Configuration

The new CommandLine.execute and CommandLine.tryExecute methods are instance methods. The older run, call and invoke methods are static methods. Static methods don’t allow configuration. The new API lets applications configure the parser or other aspects before execution.

Clone this wiki locally