有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

macos如何从Java运行与自制或MacPorts一起安装的工具?

  • 我正在尝试用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

共 (1) 个答案

  1. # 1 楼答案

    在读了太多关于贝壳的文章,研究了shell init diagrams之后,我决定选择Zsh

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

    我将所有环境设置(路径和语言)移到了/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作为根
    • SSH作为用户
    • 终点站。应用程序
    • 从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