【发布时间】:2021-07-20 16:31:57
【问题描述】:
我正在 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 的 CommandLine 实例
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;
}
}
【问题讨论】:
-
我认为一些代码可以很好地重现问题。
-
请提供重现问题的步骤,最好显示您的程序代码和指定为输入的命令行参数的完整列表。
-
感谢您的反馈,添加了一些我认为相关的代码。
标签: java spring-boot maven command-line-interface picocli