从昨天开始,我一直在尝试使用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();
}
这给我带来了以下异常
我在网上搜索,人们说source不会像这样工作,我应该将命令更改为无法运行程序“source”:错误=2,没有这样的文件或目录
String[] command = new String[] { "bash -c 'source activate abc_env'", "python example.py"};
现在,我没有收到异常,但是命令仍然无法正常工作,并且返回exitValue()为'2'
然后我尝试将命令作为脚本执行
#!/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
错误输出:/bin/bash:activate:没有这个文件或目录
如果我使用单引号将'source activate abc_env'括起来执行同样的命令,则会得到以下输出
返回值:127
错误输出:/bin/bash:source activate cvxpy_env:未找到命令
解决方案:
String[] command = {
"/bin/bash",
"-c",
"source /Users/pc_name/my_python_library/bin/activate abc_env;python example.py"
};
source /opt/anaconda/bin/activate abc_env
。 - Ioannis Koumarelas