如何在 Spring 中执行 pyomo 模型脚本?
How to execute a pyomo model script inside Spring?
我有一个使用 Spring 构建的 Web 界面,我想从中执行命令 "python file.py"。
主要问题是 file.py 内部有一个 pyomo 模型应该提供一些输出。如果它是一个简单的打印或其他东西,我可以执行一个 python 脚本,但是 pyomo 模型被完全忽略了。
可能是什么原因?
这是我在控制器中编写的用于执行调用的代码:
@PostMapping("/execute")
public void execute(@ModelAttribute("component") @Valid Component component, BindingResult result, Model model) {
Process process = null;
//System.out.println("starting!");
try {
process = Runtime.getRuntime().exec("python /home/chiara/Documents/GitHub/Pyomo/Solver/test/sample.py");
//System.out.println("here!");
} catch (Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println("stdout: " + line);
}
} catch (IOException e) {
System.out.println("Exception in reading output" + e.toString());
}
}
更新:我发现我遗漏的是我没有检查代码 运行.
的位置所以一定要这样做并最终移动输入文件(如果你在 python 执行的目录中有任何),否则脚本无法找到它们并详细说明它们。
您可以使用
cwd = os.getcwd()
检查进程的当前工作目录。
另一种可能性是在终端或日志文件中重定向 stderr,因为即使有错误,从服务器终端你也看不到任何东西。
问题中发布的代码是从 java.
调用 bash 命令的正确方法
我有一个使用 Spring 构建的 Web 界面,我想从中执行命令 "python file.py"。
主要问题是 file.py 内部有一个 pyomo 模型应该提供一些输出。如果它是一个简单的打印或其他东西,我可以执行一个 python 脚本,但是 pyomo 模型被完全忽略了。
可能是什么原因?
这是我在控制器中编写的用于执行调用的代码:
@PostMapping("/execute")
public void execute(@ModelAttribute("component") @Valid Component component, BindingResult result, Model model) {
Process process = null;
//System.out.println("starting!");
try {
process = Runtime.getRuntime().exec("python /home/chiara/Documents/GitHub/Pyomo/Solver/test/sample.py");
//System.out.println("here!");
} catch (Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println("stdout: " + line);
}
} catch (IOException e) {
System.out.println("Exception in reading output" + e.toString());
}
}
更新:我发现我遗漏的是我没有检查代码 运行.
的位置所以一定要这样做并最终移动输入文件(如果你在 python 执行的目录中有任何),否则脚本无法找到它们并详细说明它们。
您可以使用
cwd = os.getcwd()
检查进程的当前工作目录。 另一种可能性是在终端或日志文件中重定向 stderr,因为即使有错误,从服务器终端你也看不到任何东西。
问题中发布的代码是从 java.
调用 bash 命令的正确方法