command-line-interface - 文本格式不适用于 CLI - 使用 PICOCLI java
问题描述
我一直在尝试在CLI上显示格式化文本。我尝试了picocli docs (doc link)中提供的完全相同的代码,但似乎没有应用格式。
请帮助我找出我的错误。
预期产出
我的代码
import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Ansi;
@Command(name = "test", mixinStandardHelpOptions = true, version = "test 1.0",
description = "Custom @|bold,underline styles|@ and @|fg(red) colors|@.")
public class Interpreter implements Callable<Integer> {
@Override
public Integer call() throws Exception { // your business logic goes here...
String str = Ansi.AUTO.string("@|red Hello, colored world!|@");
System.out.println(str);
return 0;
}
public static void main (String[] args) {
CommandLine prompt = new CommandLine(new Interpreter());
int exitCode = prompt.execute(args);
System.exit(exitCode);
}
我的输出(未应用格式)
PS。我使用picocli v 4.5.2,将项目导出为可运行 jar,并使用Launch4j将其构建为.exe。在 Windows 10 的命令提示符下执行结果exe。
解决方案
要在 Windows 中获得 ANSI 颜色,您需要做一些额外的工作。最好的方法是将Jansi库添加到您的类路径中。
要使用 Jansi,您需要在您的应用程序中启用它:
import org.fusesource.jansi.AnsiConsole;
// ...
public static void main(String[] args) {
AnsiConsole.systemInstall(); // enable colors on Windows
new CommandLine(new Interpreter()).execute(args);
AnsiConsole.systemUninstall(); // cleanup when done
}
如果您有兴趣使用GraalVM(而不是使用 Launch4j)创建本机 Windows CLI 可执行文件,请注意 Jansi 本身不足以显示颜色。这部分是因为 GraalVM 需要配置,部分是因为 Jansi 内部依赖于非标准系统属性,如果这些属性不存在(就像 GraalVM 中的情况),则没有优雅的回退。
在修复此问题之前,您可能有兴趣将 Jansi 与picocli-jansi-graalvm结合使用。示例用法:
import picocli.jansi.graalvm.AnsiConsole; // not org.fusesource.jansi.AnsiConsole
// ...
public static void main(String[] args) {
int exitCode;
try (AnsiConsole ansi = AnsiConsole.windowsInstall()) {
exitCode = new CommandLine(new Interpreter()).execute(args);
}
System.exit(exitCode);
}
另请参阅有关Windows 中 ANSI 颜色的 picocli 用户手册部分。
推荐阅读
- python - 自定义启动指令以触发谷歌助手
- python - 在缺失数字中插入 1 的问题
- javascript - Ajax 调用成功但 $_POST['value'] 为空
- linux - Nginx 服务器没有重启
- mysql - MYSQL 3 连续出现基于年份的记录
- verilog - 8 位 CPU 和内存读取的时钟周期
- android - 如何将点击功能添加到回收站视图?
- powershell - 使用 AZ Powershell 模块注册本机应用程序
- javascript - 我希望能够在网络上查看闭路电视屏幕
- pycharm - 如何在 Pycharm 中使用 Anaconda 基础环境?