【问题标题】:How to run tools installed with Homebrew or MacPorts from Java?如何从 Java 运行使用 Homebrew 或 MacPorts 安装的工具?
【发布时间】:2021-08-09 18:42:12
【问题描述】:
  • 我正在尝试使用 Java 在 MacOS 上进行一些自动化操作。
  • 从终端手动运行命令时没有问题
  • 我认为它可以工作是因为<user.home>/.zprofile
  • 尝试通过 ProcessBuilder 执行命令时找不到命令

如何在与手动运行 zsh 终端相同的环境下执行命令?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Test {
  public static void main(String[] args) throws Exception {
    // these commands work
    run("/bin/sh", "-c", "echo $PATH");
    run("/bin/bash", "-c", "echo $PATH");
    run("/bin/zsh", "-c", "echo $PATH");

    // these commands all work when I run them manually in a terminal
    // but fail here with "zsh:1: command not found: ..."
    run("/bin/zsh", "-c", "node -v");
    run("/bin/zsh", "-c", "npm -v");
  }

  private static void run(String... command) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);
    processBuilder.command(command);
    Process process = processBuilder.start();
    try(BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
      for(String line = br.readLine(); line != null; line = br.readLine()) {
        System.out.println(line);
      }
    }
    System.out.println("return value: " + process.waitFor());
  }
}

输出:

/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
zsh:1: command not found: node
return value: 127
zsh:1: command not found: npm
return value: 127

【问题讨论】:

  • 您可以查看此stackoverflow.com/a/318252/8462076 或指定二进制文件的完整路径(which node 用于获取node 完整路径)。但是 IMO 你真的应该考虑第一个选项 ;)

标签: java macos shell homebrew processbuilder


【解决方案1】:

在阅读了太多关于 shell 的文章,并研究了 shell init diagrams 之后,我决定使用 Zsh。

原因是this blog post,这表明Zsh 似乎至少有一个初始化文件,它为所有可能的shell 变体执行(登录、非登录、交互、非交互等) )。

我将所有环境设置(PATH 和 LANG)移至 /etc/zshenv,删除了 /etc/zprofile 和所有 ~/.z* 文件。

我也changed the shell for both root and my user给Zsh(for the user this can also be done via system preferences):

  dscl . -delete /Users/root UserShell && dscl . -create /Users/root UserShell /bin/zsh && dscl . -read /Users/root UserShell
  dscl . -delete /Users/reto UserShell && dscl . -create /Users/reto UserShell /bin/zsh && dscl . -read /Users/reto UserShell

现在我得到了相同的环境:

  • SSH 以 root 身份
  • SSH 用户
  • Terminal.app
  • 从 Java 启动的进程
  • 到目前为止几乎所有其他内容

到目前为止一切顺利。测试程序输出:

/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
return value: 0
v14.17.0
return value: 0
6.14.13
return value: 0

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多