问题描述
我正在 picocli 中编写一个 CLI 应用程序,它将执行用户指定的操作次数,然后在此之后正常退出。然而,当程序退出 picocli 时,即使程序已经识别出选项已成功运行,也会打印“未知选项”错误。
UnkNown options: '-j','~/example_dir/example.json'
Usage: <main class> [-h] [COMMAND]
-h,--help Prints this help message and exits
Commands:
example_command does things
Process finished with exit code 0
知道为什么会这样吗?
以下是代码结构的大纲:
Command Line Runner,创建 Picocli 的命令行实例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.stereotype.Component;
import picocli.CommandLine;
@Component
public class ApplicationRunner implements CommandLineRunner,ExitCodeGenerator {
private int exitCode;
@Autowired
private CommandSample commandSample;
@Override
public void run(String... args) throws Exception {
exitCode = new CommandLine(commandSample).execute(args);
}
@Override
public int getExitCode() {
return exitCode;
}
}
Spring 启动应用程序:
@SpringBootApplication
public class SpringApp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SpringApp.class);
app.setBannerMode(Banner.Mode.OFF);
System.exit(SpringApplication.exit(app.run(args)));
}
}
CommandSample 类中的选项,这是正确的@Command
@Command(
description = "Publish Specified Test JSON to Specified Topics",mixinStandardHelpOptions = true,version = "beta"
)
@Controller
public class CommandSample implements Runnable,ExitCodeGenerator{
@Option(
names = {"-j","--json"},paramLabel = "<PATH_TO_JSON>",description = "Absolute Path to the JSON Payload,supports '~' as an alias for home directory"
)
private String path_to_JSON;
@Option(
names = {"-t","--topic"},paramLabel = "<MQTT_TOPIC>",description = "MQTT topic which you wish to publish to"
)
private String mqtt_topic;
@Option(
names = {"-n","--number"},paramLabel = "<NUMBER_OF_REQUESTS>",description = "Number of times to publish to topic before exiting",defaultValue = "5"
)
private long number_of_requests = 5;
@Option(
names = {"-i","--interval"},paramLabel ="<INTERVAL_BETWEEN_PUBLISH>",description = "Interval between individual publishes (in milliseconds)"
)
private long sleep_time_ms = 5000L;
@Override
public void run() {
// Some MQTT stuff
}
int exitcode;
@Override
public int getExitCode() {
return exitcode;
}
}
解决方法
有趣的是,问题归结为我在加载主要 picocli-4.6.1 依赖项后包含了以下依赖项。其中可能已经包含了这个版本的最新版本。
我的 pom.xml 中的违规依赖:
<dependency>
<groupId>com.kakawait</groupId>
<artifactId>picocli-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>