【问题标题】:Text formating is not applied in CLI - using PICOCLI javaCLI 中未应用文本格式 - 使用 PICOCLI java
【发布时间】:2020-11-11 08:28:45
【问题描述】:

我一直在尝试在 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,将项目导出为 runnable jar,然后使用 .exe 将其构建为Launch4j。 在windows 10的命令提示符下执行结果exe

【问题讨论】:

    标签: command-line-interface picocli


    【解决方案1】:

    要在 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 本身就是insufficient 以显示颜色。这部分是因为 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);
    }
    

    另请参阅ANSI colors in Windows 上的 picocli 用户手册部分。

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2021-11-07
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多