首页 > 解决方案 > 文本格式不适用于 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

标签: command-line-interfacepicocli

解决方案


要在 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 用户手册部分。


推荐阅读