【发布时间】:2015-07-12 18:31:54
【问题描述】:
从昨天开始,我一直在尝试使用 JAVA 在终端 (MAC) 上执行命令,但无论我做什么都没有用。
我想要执行以下 2 个命令并在 JAVA 中返回输出
source activate abc_env
python example.py
到目前为止,我已经尝试了以下方法,没有任何输出
String[] command = new String[] { "source activate abc_env", "python example.py"};
String result = executeCommands(command);
这是我的 executeCommands 方法
private static String executeCommands(String[] command) {
StringBuffer output = new StringBuffer();
Process p;
try {
for(int i=0; i< command.length;i++)
{
p = Runtime.getRuntime().exec(command[i]);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("Error output: " + p.exitValue());
System.out.println("Output:" + output);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Here");
}
return output.toString();
}
这给了我以下异常
无法运行程序“源”:错误=2,没有这样的文件或目录
我在网上搜索,有人说源不会这样工作,我应该将命令更改为
String[] command = new String[] { "bash -c 'source activate abc_env'", "python example.py"};
现在,我没有收到异常,但命令仍然不起作用,它返回 '2' 作为 exitValue()
然后我尝试将命令作为脚本执行
#!/bin/bash
source activate abc_env
python example.py
当我将 .sh 文件作为字符串读取并将其传递给命令时,出现以下异常
无法运行程序“#!/bin/bash”:错误=2,没有这样的文件或目录
那么,我的问题是如何通过 Java 正确运行源命令和 python 命令?我的最终目标是从 Java 中执行一些 python。
编辑1: 如果我尝试以下命令并打印输出流
String[] command = {
"/bin/bash",
"-c",
"source activate cvxpy_env"
};
executeCommand(command));
输出流:
退出值:1
ErrorOutput:/bin/bash: activate: 没有这样的文件或目录
如果我尝试相同的命令,但在 'source activate abc_env' 周围加上单引号。我得到以下输出
退出值:127
ErrorOutput:/bin/bash: source activate cvxpy_env: command not found
解决方案:
String[] command = {
"/bin/bash",
"-c",
"source /Users/pc_name/my_python_library/bin/activate abc_env;python example.py"
};
【问题讨论】:
-
为了更清楚一点,linux中的这个“/Users/pc_name/my_python_library/bin/activate/”可以翻译成Anaconda的安装路径,如:“/opt/anaconda /bin/激活”。因此:
source /opt/anaconda/bin/activate abc_env(如果 abc_env 是您的环境名称)。